Building Dynamic Web 2.0 Websites with Ruby on Rails — Save 50%
Create database-driven dynamic websites with this open-source web application framework
Sinatra is a library that allows you to build almost any kind of web-based application in a very simple manner. When you code in Sinatra you’re bound only by HTTP and your Ruby knowledge. You'll obviously want to start building tiny web-applications and small services, and that's just what we'll do in this article. By the end of this article by Satish Talim, you'll be able to understand:
- what Sinatra is
- how to install Sinatra and its dependencies
- how to build a tiny web-application
- how to deploy the tiny web-app to Heroku
Sinatra is not a framework but a library i.e. a set of classes that allows you to build almost any kind of web-based solution (no matter what the complexity) in a very simple manner, on top of the abstracted HTTP layer it implements from Rack. When you code in Sinatra you’re bound only by HTTP and your Ruby knowledge. Sinatra doesn’t force anything on you, which can lead to awesome or evil code, in equal measures.
Sinatra apps are typically written in a single file. It starts up and shuts down nearly instantaneously. It doesn’t use much memory and it serves requests very quickly. But, it also offers nearly every major feature you expect from a full web framework: RESTful resources, templating (ERB, Haml/Sass, and Builder), mime types, file streaming, etags, development/production mode, exception rendering. It’s fully testable with your choice of test or spec framework. It’s multithreaded by default, though you can pass an option to wrap actions in a mutex. You can add in a database by requiring ActiveRecord or DataMapper. And it uses Rack, running on Mongrel by default.
Blake Mizerany the creator of Sinatra says that it is better to learn Sinatra before Ruby on Rails:
When you learn a large framework first, you’re introduced to an abundance of ideas, constraints, and magic. Worst of all, they start you with a pattern. In the case of Rails, that’s MVC. MVC doesn’t fit most web-applications from the start or at all. You’re doing yourself a disservice starting with it. Back into patterns, never start with them- Reference here
The simplest way to obtain Sinatra is through Rubygems. Open a command window in Windows and type:
c:> gem install sinatra
Linux/OS X the command would be:
sudo gem install sinatra
Installing its Dependencies
- Sinatra depends on the Rack gem which gets installed along with Sinatra.
- Installing Mongrel (a fast HTTP library and server for Ruby that is intended for hosting Ruby web applications of any kind using plain HTTP - http://mongrel.rubyforge.org/) is quite simple. In the already open command window, type:
c:> gem install mongrel
What are Routes?
The main feature of Sinatra is defining ‘routes’ as an HTTP verb for a path that executes an arbitrary block of Ruby code. Something like:
verb ‘path’ do
... # return/render something
Sinatra’s routes are designed to respond to the HTTP request methods (GET, POST, PUT, DELETE).
In Sinatra, a route is an HTTP method paired with an URL matching pattern.
These URL handlers (also called "routing") can be used to match anything from a static string (such as /hello) to a string with parameters (/hello/:name) or anything you can imagine using wildcards and regular expressions.
Each route is associated with a block. Let us look at an example:
get '/' do
.. show something ..
get '/hello/:name' do
# The /hello portion matches that portion of the URL from the
# request you made, and :name will absorb any other text you
# give it and put it in the params hash under the key :name
post '/' do
.. create something ..
put '/' do
.. update something ..
delete '/' do
.. delete something ..
Routes are matched in the order they are defined.
When a new request comes in, the first route that matches the request is invoked i.e. the handler (the code block) attached to that route gets executed. For this reason, you should put your most specific handlers on top and your most vague handlers on the bottom.
A tiny web-application
Here’s an example of a simple Sinatra application. Write a Ruby program myapp1.rb and store it in the folder:
Though the name of the folder is c:>sinatra_programs, we are going to have only one Sinatra program here.
The program is:
Sinatra applications can be run directly:
ruby myapp1.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-s HANDLER]
The above options are:
- -h # help
- -p # set the port (default is 4567)
- -e # set the environment (default is development)
- -s # specify rack server/handler (default is thin)
- -x # turn on the mutex lock (default off) – currently not used
In the article- http://gist.github.com/54177, it states that using: require ‘rubygems’, is wrong. It is an environmental issue and not an app issue. The article mentions that you might It is an environmental issue and not an app issue. The article mentions that you might use: ruby -rubygems myapp1.rb
Another way is to use RUBYOPT. Refer article – http://rubygems.org/read/chapter/3.
By setting the RUBYOPT environment variable to the value rubygems, you tell Ruby to load RubyGems every time it starts up. This is similar to the -rubygems options above, but you only have to specify this once (rather than each time you run a Ruby script).
|Create database-driven dynamic websites with this open-source web application framework|
eBook Price: €16.99
Book Price: €26.99
Unix users will want to put the following line in their .profile (or equivalent):
Windows users will want to set the RUBYOPT environment variable using the appropriate system utility. (On XP you can find it under Settings / Control Panel / System. Click the advanced tab and then the "Environment Variables" button near the bottom. Note that the one-click installer will set up RUBYOPT for you automatically (unless you request it not be done).
Now let us run our trivial Sinatra application. Open a command window (I am using a Windows XP box) and type:
c:sinatra_programs> ruby myapp1.rb
== Sinatra/0.9.4 has taken the stage on 4567 for development with
backup from Mongrel
Next open a browser window and type http://localhost:4567/
Note that Sinatra uses port 4567.
Sinatra does not support application reloading and you need to stop the server and re-start it every time you make a change to the myapp1.rb application.
Rack aims to provide a minimal API for connecting web application servers (Mongrel in my case) and web frameworks (Sinatra). Our Ruby web application myapp1.rb is built using the web framework Sinatra. Sinatra is built on top of Rack. Thus myapp1.rb is a Rack app. Here, the web application server Mongrel runs our Rack app myapp1.rb. Rack supports "middleware" - components that sit between the server and your application, monitoring and/or manipulating the HTTP request/response.
When we type http://localhost:4567/ in a browser window, a HTTP GET request is sent to the application myapp1.rb
You should see the following in your browser window:
The above screenshots suggests writing a get handler. Let’s do that by writing a new file myapp2.rb :
get '/' do
# do something
The above get handler is purposely kept empty. Press Ctrl-Break in the open command window (for Windows XP). Next, type:
c:sinatra_programs> ruby myapp2.rb
Refresh the browser page (http://localhost:4567/) and you will see a blank page.
Next, let us do something in the get handler. Now write a new file myapp3.rb as follows:
get '/' do
‘Welcome from RubyLearning!’
Press Ctrl-Break in the open command window (for Windows XP). Next, type:
c:sinatra_programs> ruby myapp3.rb
Refresh the browser page and you should see "Welcome from RubyLearning!" in the browser window.
This happens because when you use the above URL, Sinatra runs the get block and will return whatever you put inside it, to the web browser.
Next, in the command window, press Ctrl-Break to stop Sinatra and then close the command window.
Heroku is a platform for the instant deployment of Ruby applications and is one of the easiest configuration and deployment option (http://heroku.com/).
Heroku has full support for Sinatra applications. Deploying to Heroku is simply a matter of pushing to a remote git repository.
Steps to deploy to Heroku
Please ensure that you are connected to the internet and then:
- Create an account on Heroku (obviously do this only once) if you don’t have one – http://heroku.com/signup. I created one with email id: email@example.com
- Install the Heroku gem file:
gem install heroku
- Open a Bash shell in c:sinatra_programs and upload your public key (do it only once):
$ heroku keys:add
Uploading ssh public key C:Documents and SettingsA/.ssh/id_rsa.pub
Enter your Heroku credentials.
Uploading ssh public key C:Documents and SettingsA/.ssh/id_rsa.pub
You'll be prompted for your username and password the first time you run a heroku command; they'll be saved on ~/.heroku/credentials so you won't be prompted on future runs. It will also upload your public key to allow you to push and pull code.
- In order for Heroku to know what to do with your Sinatra app, create a config.ru (ru stands for Rack up) in the root-directory. The contents are:
The key line is require 'myapp3'. Be sure to change that to whatever your application’s name is. This line helps to load rubygems, Sinatra, rack and everything that we need. Heroku sets RACK_ENV to production for you. Finally we tell rack to run our Sinatra application with the following line (this will run "myapp3" in our case):
- Set up your local app to use Git (if you aren't already using it). I have my myapp3.rb and config.ru files already in c:sinatra_programs - now type the following:
$ git init
$ git add .
$ git commit -m 'myapp3 first commit'
The location of the config.ru file is not $HOME, but the top directory (where you ran "git init").
- Create the app on heroku.
$ heroku create --remote
The final line of output from the create command will be different for each one of you and is something like this:
The app has been created and two URLs are provided: one for the web face of your new app, and one for the Git repository that you will push your code to.
- To get a list of apps you have created or are a collaborator on:
$ heroku list
(You would see a different list.)
- Cut and paste the second URL (from step 6) to add a Git remote:
$ git remote add starkfog firstname.lastname@example.org:stark-fog-55.git
(Remember to use your specific URL.)
- Deploy your code:
$ git push starkfog master
$ heroku info --app stark-fog-55
Git Repo: email@example.com:stark-fog-55.git
(Please use your app name in place of stark-fog-55.)
- Open the deployed app in your browser:
Open a new browser window and type http://stark-fog-55.heroku.com/
You should see Welcome from RubyLearning! in the browser window.
Congrats, you have successfully deployed your first Sinatra app.
For other deployment options, refer the URL –http://www.sinatrarb.com/book.html#deployment
In this article we have explored Sinatra, covered its installation and its dependencies, and then went on to build a tiny web-application which we deployed on Heroku.
Sinatra homepage –
Sinatra Documentation –
HTTP Made Really Easy –
List of applications, libraries, websites and companies using Sinatra –
Rubyists using Sinatra –
20+ Rubyists are using Sinatra – Do you?
What are the 12 rules of Sinatra?
Twelve Rules of Sinatra
|A step-by-step tutorial to building web mashups|
eBook Price: €20.99
Book Price: €34.99
About the Author :
Satish Talim is a senior software consultant based in Pune, India with over 32+ years of I.T. experience. His experience lies in developing and executing business for high technology and manufacturing industry customers. His strengths lie in Business Development and Business Networking apart from new product and solution ideas. Along with good experience of organization development, he has excellent cross disciplinary background in engineering, computer science and management. He has helped start subsidiaries for many US based software companies like Infonox and Servient Inc.
He has been associated with Java / J2EE since 1995 and involved with Ruby and Ruby on Rails since 2005. He has started and manages two very active Java (PuneJava) and Ruby (PuneRuby) User Groups in Pune, India. He is a Ruby Mentor on rubyforge.org, helping people with Ruby programming. Recently, he has written an eBook – “Introduction to Sinatra”, available at – http://rubylearning.com/blog/introduction-to-sinatra-ebook/. He can be contacted at http://satishtalim.com/.
Books From Packt