Using Sinatra: Building a Web Application (part ll)


Hi There! in the previous article you learned about setting up Sinatra and HTTP request methods.In this article we will use the things that we learned to build a web app. I've changed my mind about "Scissor ,Paper ,Rock " game.We'll now be encrypting and decrypting a key using my algorithm and will learn the basic of ERB.


What's ERB ?

"Embedded Ruby is a templating system that embeds Ruby into a text document. It is often used to embed Ruby code in an HTML document, similar to ASP, JSP and PHP."So we'll be embeding our code on a HTML Page.

ERB Syntax :

The key concept of ERB is simple: it allows you to write HTML with bits of Ruby code interspersed with regular HTML. Before the template is sent back to the user, it's compiled. This means that any Ruby code in the template is executed, and all we're left with is regular HTML.


like this:

<h1>Today's date is <%= Time.now %> </h1>

The ruby codes are written "<% here %>".

Some more examples:

<% 5.times do %>
  <h1>Today's date is <%= Time.now %> </h1>
<% end %>

So lets get started.
 Before we proceed,lets have a look at the Directory Structure of the project.




i) PROJECT_DIR/view − The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser.
ii)PROJECT_DIR/app.rb - This is where we be writing codes and handing HTTP requests.

Work Flow:


 So the app.rb will be handling the request and displaying the erb files as per the requests.

The Idea of the Algorithm :

-  I have three arrays (@@key1 ,@@key2,@@key3) and an array of alphabets   '@@letters'.

 For Cipher :
-Take input as String.

- I generate random numbers between 0 and 2, suppose if n comes then I choose the @@key[n] array and  then I pull out the index of all the alphabets of input by comparing it  with @@letters array and then further I  compare it with @@key array replace the elements of the input.

 


     def encode(key)       #method for encoding

           req_key=key.downcase.split("")  #converting into downcase and spliting
           key_val=rand(1..3)        #generating random numbers
           gen_key=Array.new      #creating an array to hold the index

        i=0
    if key_val==1              #if generated random numbers=1,
           while i<req_key.length
           gen_key.push(@@letters.index(req_key[i]))  #pushing index by comparing with @@letters 
                   i+=1
           end

          s=match(gen_key,@@key1)   #matching and replacing the elements with @@key array  

       elsif key_val==2          #if generated random numbers=1 
              while i<req_key.length
                gen_key.push(@@letters.index(req_key[i]))
                 i+=1
                 end
                s=match(gen_key,@@key2)

      elsif key_val==3
        while i<req_key.length
           gen_key.push(@@letters.index(req_key[i]))
           i+=1
        end
       s=match(gen_key,@@key3)
            end


    @final_key="#{@@letters[key_val-1]}#{s}"
      return @final_key
end 

 - Everytime I want to cipher my text ,different output will be produced.
 - The Decipher key is the random number generated,I'll use that to know which array elements replaced the text. 

For Decipher :
-  We Will take the input as String
-  Suppose the generate output after cipher was "bwbjqomiain"(10+1key)
-  We will split the "bwbjqomiain" and slice out the first alphabet which is "b".
-  Now we will find the index of "b" in @@letters array,so its 2.Which means that the
 @@array2 elements were used to replaced the text,so we will compare the index of the input with @@array2 and push the index in an array which we further compare with the @@letters array to get the result.

def decode(key)
du=key.split("")
first=key.slice du[0]
su=key.sub(du[0],"")
ary=su.split("")
hold=Array.new
ne=Array.new
i=0
j=1
while i<ary.length && j<ary.length
ne.push("#{ary[i]}#{ary[j]}")
i+=2
j+=2
end
i=0
if first=="a"
while i<ne.length
hold.push(@@key1.index(ne[i]))
i+=1
end
#s=match(gen_key,@@key1)
elsif first=="b"
while i<ne.length
hold.push(@@key2.index(ne[i]))
i+=1
end
elsif first=="c"
while i<ne.length
hold.push(@@key3.index(ne[i]))
i+=1
end
end
@deci= match(hold,@@letters)
return @deci
end



Handling the HTTP Request:
The request will be made by the POST method,to handle
Type:


get "/" do
erb:form     #throws erb when we visit localhost
end
 Writing ERB:

 Type the following in your "views/form.erb"


<html>
<body>
<h1><center> Welcome to <i>MyCipher</i> </center></h1>
<ul>
<ul>1.Do not put any space b/w text</ul>
<ul>2.The output will be in small letters</ul>
<ul>
<p> <ul>Your Input</ul>
<p>
<form method="post" action="/function">
Select: <input type="text" name="name">
<ul>
<p>
<ul> <input type="submit" name="s1" value="Cipher Text"> </input></ul>
<p>
<ul> <input type="submit" name="s2" value="Decipher Text"> </input></ul>
</ul>
</form>
<p>
<h3><font color="blue">The Result </h3><p>
<h2><font color="red"> <%= @final_key%></h2>
<h2><font color="red"> <%= @deci%></h2> 


The User Interface would look like this:


Handling the Form :

Type following in your app.rb file :

post "/function" do
ci=params[:s1].to_s
di=params[:s2].to_s
val=params[:name].to_s
if ci!=""
encode(val)
else
decode(val)
end
erb:app
end

Voila ! Its Completed ,now its time to test it.Here is the screenshot of the working model:

Giving Input for cipher:

 
 The Resulted cipher:





The Output of Decipher:



Here's the link to the download  code . 



Special thanks to Rajat Srivastav for creating the sketch .
Take Care,Aloha!