Using Sinatra :A Web App Development Library(Part l)


Ruby is blessed with several web application frameworks such as Ruby on Rails, Merb, Nitro,  Camping and Sinatra.Many of us might have heard about Ruby on Rails ,In simple words, Sinatra is an alternative to it and the other frameworks mentioned above.Sinatra was designed and developed by Blake Mizerany in 2007 and named after musician Frank Sinatra.

In this article we'll learn about :
i.   Installing and Setting up Sinatra
ii.  Handling the HTTP Request

Prerequisites:  One Must Know Ruby to proceed further.

So let's begin :

Installing and Setting up Sinatra:
 i.  Open the Terminal.
ii.   Type "gem install sinatra" without " ".

Voila! The gem got install.Now its time to Test it.So, for this we will create  file named "app.rb" and type:

require "sinatra" #to use the sinatra module

and run the app by typing "ruby /directory_name/app.rb" without ""  and then go to the web browser and type in the search bar 'localhost:port_number' ,in my case its 'localhost:4567'  without '' you can find the port number on the running terminal.Then something like this will appear :
Its Hosted on RACK.

 ii.  Handling the HTTP Request

HTTP is a request protocol,When you type something in a web Browser it sends a request for some information  and the web server sends back a response.

You must've observed that when you click on Your name in your facebook's timeline then your profile gets opened , have you noticed that in the search bar ,the link gets changed to "www.facebook.com/profile" from " www.facebook.com/home ".Thats what the HTTP request is.You requested for profile page and server sent back the response by landing you on the profile page. We will discuss about the two most common HTTP Request Methods i.e. "GET and POST". HTTP POST requests supply additional data from the client (browser) to the server in the message body. In contrast, GET requests include all required data in the URL.  

Making Response to the HTTP request in Sinatra :  

To do this ,create a file "app.rb" and type:
 
require "sinatra"

get "/" do
  "This is a Home Page!"
end

get "/about" do
  "This is a about Page!"
end

get "/contact" do
  "This is a Contact Page!"
end
 
Now using GET method we are requesting for specific response, when the app.rb will be run and user will visit "localhost:4567/about" the response will be "This is about Page!".


Simillarly when we will request for the Contact page by visiting "localhost:4567/contact" we will receive a message "This is a Contact Page!".

In the next part we will be developing a smalll web application 'Scissor,Paper,Rock'
on Sinatra.

Thanks for your time, Aloha !