Sinatra Part 2: Controllers

Sinatra Part 2: Controllers

Who does not know, Sinatra – it’s minimalistic web framework written in Ruby, built on the basis of the Rack. Sinatra is perfect for the development of simple sites and services, where Rails is too excessive solution. The developers called Sinatra – «Domain Specific Language for quickly creating web-applications in Ruby».

Install Sinatra

$ gem install sinatra
Fetching: tilt-1.3.3.gem (100%)
Fetching: sinatra-1.2.6.gem (100%)
Successfully installed tilt-1.3.3
Successfully installed sinatra-1.2.6
2 gems installed

RubyGems install Sinatra Framework and gem Tilt – interface for multiple languages templates sold on Ruby (erb, haml, textile, markdown, slim, etc.).

In Sinatra, as well as in the present Rails requests: get, post, put, delete, the last two are emulated, because browsers do not support them. At a time when in Rails routing rules (routing) are stored in the file ./config/route.rb, in Sinatra routing is described directly in the fact that I, with your permission, call controller. Routing looks like this:

<request> 'pattern' do
  # do anything
end

For example:

#./app.rb
require 'sinatra'
 
get '/' do
  "Welcome to DevBattles.com"
end

Run:

$ ruby app.rb
== Sinatra/1.2.6 has taken the stage on 4567 for development with backup from WEBrick
[2011-09-25 18:33:45] INFO  WEBrick 1.3.1
[2011-09-25 18:33:45] INFO  ruby 1.9.2 (2011-02-18) [i686-linux]
[2011-09-25 18:33:45] INFO  WEBrick::HTTPServer#start: pid=4785 port=4567

Named parameters routing implemented in a similar way as in Rails – through symbols – keys to access the options:

require 'sinatra'
 
get '/' do
  "Welcome to DevBattles.com"
end
 
get '/:id' do
  "Article ##{params[:id]}"
end

In going to the address http://localhost:4567/12 we will see the text: «Article # 12″.

The anonymous (splat) parameters. example:

get '/' do
  "Welcome to DevBattles.com"
end
 
get '/:id' do
  "Article ##{params[:id]}"
end
 
get '/*/edit' do
  "Edit #{params[:splat].first}"
end

In going to the address http://localhost:4567/hello/ edit text we see «Edit hello».

Named and splat parameters can be used not only by using the params, but using arguments code block. To demonstrate rewrite the example above:

require 'sinatra'
 
get '/' do
  "Welcome to DevBattles.com"
end
 
get '/:id' do |id|
  "Article ##{id}"
end
 
get '/*/edit' do |prop|
  "Edit #{prop}"
end

This example is fully equivalent to the example above.
Note: Parameter :id Sinatra in default should only be an integer type.

Filters

In Sinatra, as well as in Rails controllers are available before and after the filter.

Example:

require 'sinatra'
 
before do
  @title = "Sinatra Tutorial"
end
 
before '/' do
  @welcome = "Welcome to DevBattles.com"
end
 
get '/' do
  "#{@title}<br />#{@welcome}"
end
 
get '/:id' do |id|
  #@welcome not determined
  "#{@title}<br />#{@welcome}"
end
 
get '/*/edit' do |prop|
  "#{@title}<br />Edit #{prop}"
end