Building tiny Web-applications in Ruby using Sinatra

Exclusive offer: get 50% off this eBook here
Building Dynamic Web 2.0 Websites with Ruby on Rails

Building Dynamic Web 2.0 Websites with Ruby on Rails — Save 50%

Create database-driven dynamic websites with this open-source web application framework

$20.99    $10.50
by Satish Talim | August 2009 | Open Source

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

What’s Sinatra?

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

Installing Sinatra

    

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

  1. Sinatra depends on the Rack gem which gets installed along with Sinatra.
  2. 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
end

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 ..
end
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
end
post '/' do
.. create something ..
end

put '/' do
.. update something ..
end
delete '/' do
.. delete something ..
end

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:

c:sinatra_programs

Though the name of the folder is c:>sinatra_programs, we are going to have only one Sinatra program here.

The program is:

# myapp1.rb
require 'sinatra'

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).

Building Dynamic Web 2.0 Websites with Ruby on Rails Create database-driven dynamic websites with this open-source web application framework
Published: March 2008
eBook Price: $20.99
Book Price: $34.99
See more
Select your format and quantity:

Unix users will want to put the following line in their .profile (or equivalent):

export RUBYOPT=rubygems

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:

Sinatra

The above screenshots suggests writing a get handler. Let’s do that by writing a new file myapp2.rb :

# myapp2.rb
require 'sinatra'
get '/' do
# do something
end

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:

# myapp3.rb
require 'sinatra'
get '/' do
‘Welcome from RubyLearning!’
end

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.

Deployment

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:

  1. 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: satish.talim@gmail.com
  2. Install the Heroku gem file:
    gem install heroku
  3. Open a Bash shell in c:sinatra_programs and upload your public key (do it only once):
    A@COMP /c/sinatra_programs
    $ heroku keys:add
    Uploading ssh public key C:Documents and SettingsA/.ssh/id_rsa.pub
    Enter your Heroku credentials.
    Email: satish.talim@gmail.com
    Password:
    Uploading ssh public key C:Documents and SettingsA/.ssh/id_rsa.pub
    A@COMP /c/sinatra_programs
    $

    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.

  4. 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:
    require "myapp3"
    run Sinatra::Application

    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):

    run Sinatra::Application
  5. 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:
    A@COMP /c/sinatra_programs
    $ 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").

  6. Create the app on heroku.
    A@COMP /c/sinatra_programs
    $ heroku create --remote
    Created http://stark-fog-55.heroku.com/ | git@heroku.com:stark-fog-55.git
    A@COMP /c/sinatra_programs
    $

    The final line of output from the create command will be different for each one of you and is something like this:

    Created http://stark-fog-55.heroku.com/ | git@heroku.com:stark-fog-55.git

    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.

  7. To get a list of apps you have created or are a collaborator on:
    A@COMP /c/sinatra_programs
    $ heroku list
    stark-fog-55
    A@COMP /c/sinatra_programs

    (You would see a different list.)

  8. Cut and paste the second URL (from step 6) to add a Git remote:
    $ git remote add starkfog git@heroku.com:stark-fog-55.git

    (Remember to use your specific URL.)

  9. Deploy your code:
    A@COMP /c/sinatra_programs
    $ git push starkfog master
    $
  10. Confirm:
    A@COMP /c/sinatra_programs
    $ heroku info --app stark-fog-55
    === stark-fog-55
    Web URL: http://stark-fog-55.heroku.com/
    Git Repo: git@heroku.com:stark-fog-55.git
    Collaborators: satish.talim@gmail.com
    A@COMP /c/sinatra_programs
    $

    (Please use your app name in place of stark-fog-55.)

  11. 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

Summary

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.

Resources

Sinatra homepage
http://www.sinatrarb.com/

Sinatra Documentation
http://www.sinatrarb.com/documentation.html

HTTP Made Really Easy
http://www.jmarshall.com/easy/http/

HTTP 101
http://blog.monstuff.com/archives/000149.html

Rack -
http://rack.rubyforge.org/

Introduction to Rack
http://m.onkey.org/2008/11/17/ruby-on-rack-1
http://www.railsenvy.com/2009/6/11/rack-metal-and-rails-middleware/
http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html

List of applications, libraries, websites and companies using Sinatra
http://www.sinatrarb.com/wild.html

Interviews of people working with Sinatra
Interview: Ryan Tomayko on Sinatra
Interview: Adam Wiggins on Heroku
Follow Cost: A Sinatra app for Twitter

Rubyists using Sinatra
20+ Rubyists are using Sinatra – Do you?

How do I learn and master Sinatra?
How do I learn and master Sinatra?
Jeremy Evans: How do I learn and master Sinatra?
Graham Ashton: How do I learn and master Sinatra?

What are the 12 rules of Sinatra?
Twelve Rules of Sinatra

Ruby on Rails Web Mashup Projects A step-by-step tutorial to building web mashups
Published: April 2008
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

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

Aptana RadRails: An IDE for Rails Development
Aptana RadRails: An IDE for Rails Development

Joomla! 1.5 Template Design
Joomla! 1.5 Template Design

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

Drools JBoss Rules 5.0 Developer's Guide
Drools JBoss Rules 5.0 Developer's Guide

Drupal 6 Site Blueprints
Drupal 6 Site Blueprints

ASP.NET 3.5 CMS Development
ASP.NET 3.5 CMS Development

Apache Struts 2 Web Application Development
Apache Struts 2 Web Application Development

Ruby on Rails Enterprise Application Development: Plan, Program, Extend
Ruby on Rails Enterprise Application Development: Plan, Program, Extend

 

Your rating: None Average: 4 (1 vote)
Ruby development on Windows!?!?! by
Yeah, right. How about using the OS that portential readers of this article/book actuall use? It's either Linux based, or OS/X. No one uses Windows for Ruby/Rails development, unless they don't have a choice.

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
C
h
w
2
U
5
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software