Skip to content
bmizeranyPublic
forked from sinatra/sinatra

About

(offically at github.com/sinatra/sinatra) Classy web-development dressed in a DSL

Resources

Stars

910 stars

Watchers

27 watching

Forks

 
 

Repository files navigation

Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort:

# myapp.rb
require 'sinatra'

get '/' do
  'Hello world!'
end

Install the gem and run with:

gem install sinatra
ruby -rubygems myapp.rb

View at: localhost:4567

It is recommended to also run gem install thin, which Sinatra will pick up if available.

In Sinatra, a route is an HTTP method paired with a URL-matching pattern. Each route is associated with a block:

get '/' do
  .. show something ..
end

post '/' do
  .. create something ..
end

put '/' do
  .. replace something ..
end

patch '/' do
  .. modify something ..
end

delete '/' do
  .. annihilate something ..
end

options '/' do
  .. appease something ..
end

Routes are matched in the order they are defined. The first route that matches the request is invoked.

Route patterns may include named parameters, accessible via the params hash:

get '/hello/:name' do
  # matches "GET /hello/foo" and "GET /hello/bar"
  # params[:name] is 'foo' or 'bar'
  "Hello #{params[:name]}!"
end

You can also access named parameters via block parameters:

get '/hello/:name' do |n|
  "Hello #{n}!"
end

Route patterns may also include splat (or wildcard) parameters, accessible via the params[:splat] array:

get '/say/*/to/*' do
  # matches /say/hello/to/world
  params[:splat] # => ["hello", "world"]
end

get '/download/*.*' do
  # matches /download/path/to/file.xml
  params[:splat] # => ["path/to/file", "xml"]
end

Or with block parameters:

get '/download/*.*' do |path, ext|
  [path, ext] # => ["path/to/file", "xml"]
end

Route matching with Regular Expressions:

get %r{/hello/([\w]+)} do
  "Hello, #{params[:captures].first}!"
end

Or with a block parameter:

get %r{/hello/([\w]+)} do |c|
  "Hello, #{c}!"
end

Route patterns may have optional parameters:

get '/posts.?:format?' do
  # matches "GET /posts" and any extension "GET /posts.json", "GET /posts.xml" etc.
end

By the way, unless you disable the path traversal attack protection (see below), the request path might be modified before matching against your routes.

Routes may include a variety of matching conditions, such as the user agent:

get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
  "You're using Songbird version #{params[:agent][0]}"
end

get '/foo' do
  # Matches non-songbird browsers
end

Other available conditions are host_name and provides:

get '/', :host_name => /^admin\./ do
  "Admin Area, Access denied!"
end

get '/', :provides => 'html' do
  haml :index
end

get '/', :provides => ['rss', 'atom', 'xml'] do
  builder :feed
end

You can easily define your own conditions:

set(:probability) { |value| condition { rand <= value } }

get '/win_a_car', :probability => 0.1 do
  "You won!"
end

get '/win_a_car' do
  "Sorry, you lost."
end

For a condition that takes multiple values use a splat:

set(:auth) do |*roles|   # <- notice the splat here
  condition do
    unless logged_in? && roles.any? {|role| current_user.in_role? role }
      redirect "/login/", 303
    end
  end
end

get "/my/account/", :auth => [:user, :admin] do
  "Your Account Details"
end

get "/only/admin/", :auth => :admin do
  "Only admins are allowed here!"
end

The return value of a route block determines at least the response body passed on to the HTTP client, or at least the next middleware in the Rack stack. Most commonly, this is a string, as in the above examples. But other values are also accepted.

You can return any object that would either be a valid Rack response, Rack body object or HTTP status code:

  • An Array with three elements: [status (Fixnum), headers (Hash), response body (responds to #each)]

  • An Array with two elements: [status (Fixnum), response body (responds to #each)]

  • An object that responds to #each and passes nothing but strings to the given block

  • A Fixnum representing the status code

That way we can, for instance, easily implement a streaming example:

class Stream
  def each
    100.times { |i| yield "#{i}\n" }
  end
end

get('/') { Stream.new }

You can also use the stream helper method (described below) to reduce boiler plate and embed the streaming logic in the route.

As shown above, Sinatra ships with built-in support for using String patterns and regular expressions as route matches. However, it does not stop there. You can easily define your own matchers:

class AllButPattern
  Match = Struct.new(:captures)

  def initialize(except)
    @except   = except
    @captures = Match.new([])
  end

  def match(str)
    @captures unless @except === str
  end
end

def all_but(pattern)
  AllButPattern.new(pattern)
end

get all_but("/index") do
  # ...
end

Note that the above example might be over-engineered, as it can also be expressed as:

get // do
  pass if request.path_info == "/index"
  # ...
end

Or, using negative look ahead:

get %r{^(?!/index$)} do
  # ...
end

Static files are served from the ./public directory. You can specify a different location by setting the :public_folder option:

set :public_folder, File.dirname(__FILE__) + '/static'

Note that the public directory name is not included in the URL. A file ./public/css/style.css is made available as http://example.com/css/style.css.

Use the :static_cache_control setting (see below) to add Cache-Control header info.

Each template language is exposed as via its own rendering method. These methods simply return a string:

get '/' do
  erb :index
end

This renders views/index.erb.

Instead of a template name, you can also just pass in the template content directly:

get '/' do
  code = "<%= Time.now %>"
  erb code
end

Templates take a second argument, the options hash:

get '/' do
  erb :index, :layout => :post
end

This will render views/index.erb embedded in the views/post.erb (default is views/layout.erb, if it exists).

Any options not understood by Sinatra will be passed on to the template engine:

get '/' do
  haml :index, :format => :html5
end

You can also set options per template language in general:

set :haml, :format => :html5

get '/' do
  haml :index
end

Options passed to the render method override options set via set.

Available Options:

locals

List of locals passed to the document. Handy with partials. Example: erb "<%= foo %>", :locals => {:foo => "bar"}

default_encoding

String encoding to use if uncertain. Defaults to settings.default_encoding.

views

Views folder to load templates from. Defaults to settings.views.

layout

Whether to use a layout (true or false), if it’s a Symbol, specifies what template to use. Example: erb :index, :layout => !request.xhr?

content_type

Content-Type the template produces, default depends on template language.

scope

Scope to render template under. Defaults to the application instance. If you change this, instance variables and helper methods will not be available.

layout_engine

Template engine to use for rendering the layout. Useful for languages that do not support layouts otherwise. Defaults to the engine used for the template. Example: set :rdoc, :layout_engine => :erb

Templates are assumed to be located directly under the ./views directory. To use a different views directory:

set :views, settings.root + '/templates'

One important thing to remember is that you always have to reference templates with symbols, even if they’re in a subdirectory (in this case, use :'subdir/template'). You must use a symbol because otherwise rendering methods will render any strings passed to them directly.

Some languages have multiple implementations. To specify what implementation to use (and to be thread-safe), you should simply require it first:

require 'rdiscount' # or require 'bluecloth'
get('/') { markdown :index }
Dependency

haml

File Extensions

.haml

Example

haml :index, :format => :html5

Dependency

erubis or erb (included in Ruby)

File Extensions

.erb, .rhtml or .erubis (Erubis only)

Example

erb :index

Dependency

builder

File Extensions

.builder

Example

builder { |xml| xml.em "hi" }

It also takes a block for inline templates (see example).

Dependency

nokogiri

File Extensions

.nokogiri

Example

nokogiri { |xml| xml.em "hi" }

It also takes a block for inline templates (see example).

Dependency

sass

File Extensions

.sass

Example

sass :stylesheet, :style => :expanded

Dependency

sass

File Extensions

.scss

Example

scss :stylesheet, :style => :expanded

Dependency

less

File Extensions

.less

Example

less :stylesheet

Dependency

liquid

File Extensions

.liquid

Example

liquid :index, :locals => { :key => 'value' }

Since you cannot call Ruby methods (except for yield) from a Liquid template, you almost always want to pass locals to it.

Dependency

rdiscount, redcarpet, bluecloth, kramdown or maruku

File Extensions

.markdown, .mkd and .md

Example

markdown :index, :layout_engine => :erb

It is not possible to call methods from markdown, nor to pass locals to it. You therefore will usually use it in combination with another rendering engine:

erb :overview, :locals => { :text => markdown(:introduction) }

Note that you may also call the markdown method from within other templates:

%h1 Hello From Haml!
%p= markdown(:greetings)

Since you cannot call Ruby from Markdown, you cannot use layouts written in Markdown. However, it is possible to use another rendering engine for the template than for the layout by passing the :layout_engine option.

Dependency

RedCloth

File Extensions

.textile

Example

textile :index, :layout_engine => :erb

It is not possible to call methods from textile, nor to pass locals to it. You therefore will usually use it in combination with another rendering engine:

erb :overview, :locals => { :text => textile(:introduction) }

Note that you may also call the textile method from within other templates:

%h1 Hello From Haml!
%p= textile(:greetings)

Since you cannot call Ruby from Textile, you cannot use layouts written in Textile. However, it is possible to use another rendering engine for the template than for the layout by passing the :layout_engine option.

Dependency

rdoc

File Extensions

.rdoc

Example

rdoc :README, :layout_engine => :erb

It is not possible to call methods from rdoc, nor to pass locals to it. You therefore will usually use it in combination with another rendering engine:

erb :overview, :locals => { :text => rdoc(:introduction) }

Note that you may also call the rdoc method from within other templates:

%h1 Hello From Haml!
%p= rdoc(:greetings)

Since you cannot call Ruby from RDoc, you cannot use layouts written in RDoc. However, it is possible to use another rendering engine for the template than for the layout by passing the :layout_engine option.

Dependency

radius

File Extensions

.radius

Example

radius :index, :locals => { :key => 'value' }

Since you cannot call Ruby methods directly from a Radius template, you almost always want to pass locals to it.

Dependency

markaby

File Extensions

.mab

Example

markaby { h1 "Welcome!" }

It also takes a block for inline templates (see example).

Dependency

slim

File Extensions

.slim

Example

slim :index

Dependency

creole

File Extensions

.creole

Example

creole :wiki, :layout_engine => :erb

It is not possible to call methods from creole, nor to pass locals to it. You therefore will usually use it in combination with another rendering engine:

erb :overview, :locals => { :text => creole(:introduction) }

Note that you may also call the creole method from within other templates:

%h1 Hello From Haml!
%p= creole(:greetings)

Since you cannot call Ruby from Creole, you cannot use layouts written in Creole. However, it is possible to use another rendering engine for the template than for the layout by passing the :layout_engine option.

Dependency

coffee-script and a way to execute javascript

File Extensions

.coffee

Example

coffee :index

Dependency

yajl-ruby

File Extensions

.yajl

Example

yajl :index, :locals => { :key => 'qux' }, :callback => 'present', :variable => 'resource'

The template source is evaluated as a Ruby string, and the resulting json variable is converted #to_json.

json = { :foo => 'bar' }
json[:baz] = key

The :callback and :variable options can be used to decorate the rendered object.

var resource = {"foo":"bar","baz":"qux"}; present(resource);
Dependency

wlang

File Extensions

.wlang

Example

wlang :index, :locals => { :key => 'value' }

Since calling ruby methods is not idiomatic in wlang, you almost always want to pass locals to it. Layouts written in wlang and yield are supported, though.

get '/' do