Find file History
Pull request Compare This branch is 441 commits behind sinatra:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.


<div class='toc'>
	<ol class='level-1'>
		<li><a href='#Routes'>Routes</a></li>
		<ol class='level-2'>
			<li><a href='#Conditions'>Conditions</a></li>
			<li><a href='#Return%20Values'>Return Values</a></li>
			<li><a href='#Custom%20Route%20Matchers'>Custom Route Matchers</a></li>
		<li><a href='#Static%20Files'>Static Files</a></li>
		<li><a href='#Views%20/%20Templates'>Views / Templates</a></li>
		<ol class='level-2'>
			<li><a href='#Haml%20Templates'>Haml Templates</a></li>
			<li><a href='#Erb%20Templates'>Erb Templates</a></li>
			<li><a href='#Erubis%20Templates'>Erubis Templates</a></li>
			<li><a href='#Builder%20Templates'>Builder Templates</a></li>
			<li><a href='#Nokogiri%20Templates'>Nokogiri Templates</a></li>
			<li><a href='#Sass%20Templates'>Sass Templates</a></li>
			<li><a href='#Scss%20Templates'>Scss Templates</a></li>
			<li><a href='#Less%20Templates'>Less Templates</a></li>
			<li><a href='#Liquid%20Templates'>Liquid Templates</a></li>
			<li><a href='#Markdown%20Templates'>Markdown Templates</a></li>
			<li><a href='#Textile%20Templates'>Textile Templates</a></li>
			<li><a href='#RDoc%20Templates'>RDoc Templates</a></li>
			<li><a href='#Radius%20Templates'>Radius Templates</a></li>
			<li><a href='#Markaby%20Templates'>Markaby Templates</a></li>
			<li><a href='#Slim%20Templates'>Slim Templates</a></li>
			<li><a href='#CoffeeScript%20Templates'>CoffeeScript Templates</a></li>
			<li><a href='#Embedded%20Templates'>Embedded Templates</a></li>
			<li><a href='#Accessing%20Variables%20in%20Templates'>Accessing Variables in Templates</a></li>
			<li><a href='#Inline%20Templates'>Inline Templates</a></li>
			<li><a href='#Named%20Templates'>Named Templates</a></li>
			<li><a href='#Associating%20File%20Extensions'>Associating File Extensions</a></li>
			<li><a href='#Adding%20Your%20Own%20Template%20Engine'>Adding Your Own Template Engine</a></li>
		<li><a href='#Filters'>Filters</a></li>
		<li><a href='#Helpers'>Helpers</a></li>
		<ol class='level-2'>
			<li><a href='#Using%20Sessions'>Using Sessions</a></li>
			<li><a href='#Halting'>Halting</a></li>
			<li><a href='#Passing'>Passing</a></li>
			<li><a href='#Triggering%20Another%20Route'>Triggering Another Route</a></li>
			<li><a href='#Setting%20Body,%20Status%20Code%20and%20Headers'>Setting Body, Status Code and Headers</a></li>
			<li><a href='#Mime%20Types'>Mime Types</a></li>
			<li><a href='#Generating%20URLs'>Generating URLs</a></li>
			<li><a href='#Browser%20Redirect'>Browser Redirect</a></li>
			<li><a href='#Cache%20Control'>Cache Control</a></li>
			<li><a href='#Sending%20Files'>Sending Files</a></li>
			<li><a href='#Accessing%20the%20Request%20Object'>Accessing the Request Object</a></li>
			<li><a href='#Attachments'>Attachments</a></li>
			<li><a href='#Looking%20Up%20Template%20Files'>Looking Up Template Files</a></li>
		<li><a href='#Configuration'>Configuration</a></li>
		<ol class='level-2'>
			<li><a href='#Available%20Settings'>Available Settings</a></li>
		<li><a href='#Error%20Handling'>Error Handling</a></li>
		<ol class='level-2'>
			<li><a href='#Not%20Found'>Not Found</a></li>
			<li><a href='#Error'>Error</a></li>
		<li><a href='#Rack%20Middleware'>Rack Middleware</a></li>
		<li><a href='#Testing'>Testing</a></li>
		<li><a href='#Sinatra::Base%20-%20Middleware,%20Libraries,%20and%20Modular%20Apps'>Sinatra::Base - Middleware, Libraries, and Modular Apps</a></li>
		<ol class='level-2'>
			<li><a href='#Modular%20vs.%20Classic%20Style'>Modular vs. Classic Style</a></li>
			<li><a href='#Serving%20a%20Modular%20Application'>Serving a Modular Application</a></li>
			<li><a href=''>Using a Classic Style Application with a</a></li>
			<li><a href=''>When to use a</a></li>
			<li><a href='#Using%20Sinatra%20as%20Middleware'>Using Sinatra as Middleware</a></li>
		<li><a href='#Scopes%20and%20Binding'>Scopes and Binding</a></li>
		<ol class='level-2'>
			<li><a href='#Application/Class%20Scope'>Application/Class Scope</a></li>
			<li><a href='#Request/Instance%20Scope'>Request/Instance Scope</a></li>
			<li><a href='#Delegation%20Scope'>Delegation Scope</a></li>
		<li><a href='#Command%20Line'>Command Line</a></li>
		<li><a href='#Requirements'>Requirements</a></li>
		<li><a href='#The%20Bleeding%20Edge'>The Bleeding Edge</a></li>
		<ol class='level-2'>
			<li><a href='#With%20Bundler'>With Bundler</a></li>
			<li><a href='#Roll%20Your%20Own'>Roll Your Own</a></li>
			<li><a href='#Install%20Globally'>Install Globally</a></li>
		<li><a href='#Further%20Reading'>Further Reading</a></li>

<p>Sinatra is a DSL for quickly creating web applications in Ruby with minimal

<pre># myapp.rb
require 'sinatra'

get '/' do
  'Hello world!'

<p>Install the gem and run with:</p>

<pre>gem install sinatra
ruby -rubygems myapp.rb</pre>

<p>View at: <a href="http://localhost:4567">localhost:4567</a></p>

<p>It is recommended to also run <tt>gem install thin</tt>, which Sinatra will
pick up if available.</p>

<a name='Routes'></a>

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

<pre>get '/' do
  .. show something ..

post '/' do
  .. create something ..

put '/' do
  .. update something ..

delete '/' do
  .. annihilate something ..

options '/' do
  .. appease something ..

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

<p>Route patterns may include named parameters, accessible via the
<tt>params</tt> hash:</p>

<pre>get '/hello/:name' do
  # matches &quot;GET /hello/foo&quot; and &quot;GET /hello/bar&quot;
  # params[:name] is 'foo' or 'bar'
  &quot;Hello #{params[:name]}!&quot;

<p>You can also access named parameters via block parameters:</p>

<pre>get '/hello/:name' do |n|
  &quot;Hello #{n}!&quot;

<p>Route patterns may also include splat (or wildcard) parameters, accessible
via the <tt>params[:splat]</tt> array.</p>

<pre>get '/say/*/to/*' do
  # matches /say/hello/to/world
  params[:splat] # =&gt; [&quot;hello&quot;, &quot;world&quot;]

get '/download/*.*' do
  # matches /download/path/to/file.xml
  params[:splat] # =&gt; [&quot;path/to/file&quot;, &quot;xml&quot;]

<p>Route matching with Regular Expressions:</p>

<pre>get %r{/hello/([\w]+)} do
  &quot;Hello, #{params[:captures].first}!&quot;

<p>Or with a block parameter:</p>

<pre>get %r{/hello/([\w]+)} do |c|
  &quot;Hello, #{c}!&quot;

<a name='Conditions'></a>

<p>Routes may include a variety of matching conditions, such as the user

<pre>get '/foo', :agent =&gt; /Songbird (\d\.\d)[\d\/]*?/ do
  &quot;You're using Songbird version #{params[:agent][0]}&quot;

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

<p>Other available conditions are <tt>host_name</tt> and <tt>provides</tt>:</p>

<pre>get '/', :host_name =&gt; /^admin\./ do
  &quot;Admin Area, Access denied!&quot;

get '/', :provides =&gt; 'html' do
  haml :index

get '/', :provides =&gt; ['rss', 'atom', 'xml'] do
  builder :feed

<p>You can easily define your own conditions:</p>

<pre>set(:probability) { |value| condition { rand &lt;= value } }

get '/win_a_car', :probability =&gt; 0.1 do
  &quot;You won!&quot;

get '/win_a_car' do
  &quot;Sorry, you lost.&quot;

<a name='Return%20Values'></a>
<h3>Return Values</h3>

<p>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.</p>

<p>You can return any object that would either be a valid Rack response, Rack
body object or HTTP status code:</p>
<p>An Array with three elements: <tt>[status (Fixnum), headers (Hash),
response body (responds to #each)]</tt></p>
<p>An Array with two elements: <tt>[status (Fixnum), response body (responds
to #each)]</tt></p>
<p>An object that responds to <tt>#each</tt> and passes nothing but strings to
the given block</p>
<p>A Fixnum representing the status code</p>

<p>That way we can, for instance, easily implement a streaming example:</p>

<pre>class Stream
  def each
    100.times { |i| yield &quot;#{i}\n&quot; }

get('/') { }</pre>

<a name='Custom%20Route%20Matchers'></a>
<h3>Custom Route Matchers</h3>

<p>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:</p>

<pre>class AllButPattern
  Match =

  def initialize(except)
    @except   = except
    @captures =[])

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

def all_but(pattern)

get all_but(&quot;/index&quot;) do
  # ...

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

<pre>get // do
  pass if request.path_info == &quot;/index&quot;
  # ...

<p>Or, using negative look ahead:</p>

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

<a name='Static%20Files'></a>
<h2>Static Files</h2>

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

<pre>set :public, File.dirname(__FILE__) + '/static'</pre>

<p>Note that the public directory name is not included in the URL. A file
<tt>./public/css/style.css</tt> is made available as <tt><a

<a name='Views%20/%20Templates'></a>
<h2>Views / Templates</h2>

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

<pre>set :views, File.dirname(__FILE__) + '/templates'</pre>

<p>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 <tt>:'subdir/template'</tt>). You must use a symbol because otherwise
rendering methods will render any strings passed to them directly.</p>

<a name='Haml%20Templates'></a>
<h3>Haml Templates</h3>

<p>The <tt>haml</tt> gem/library is required to render HAML templates:</p>

<pre># You'll need to require haml in your app
require 'haml'

get '/' do
  haml :index

<p>Renders <tt>./views/index.haml</tt>.</p>

options</a> can be set globally through Sinatra’s configurations, see <a
href="">Options and
Configurations</a>, and overridden on an individual basis.</p>

<pre>set :haml, :format =&gt; :html5 # default Haml format is :xhtml

get '/' do
  haml :index, :format =&gt; :html4 # overridden

<a name='Erb%20Templates'></a>
<h3>Erb Templates</h3>

<pre># You'll need to require erb in your app
require 'erb'

get '/' do
  erb :index

<p>Renders <tt>./views/index.erb</tt>.</p>

<a name='Erubis%20Templates'></a>
<h3>Erubis Templates</h3>

<p>The <tt>erubis</tt> gem/library is required to render Erubis templates:</p>

<pre># You'll need to require erubis in your app
require 'erubis'

get '/' do
  erubis :index

<p>Renders <tt>./views/index.erubis</tt>.</p>

<p>It is also possible to replace Erb with Erubis:</p>

<pre>require 'erubis'
Tilt.register :erb, Tilt[:erubis]

get '/' do
  erb :index

<p>Renders <tt>./views/index.erb</tt> with Erubis.</p>

<a name='Builder%20Templates'></a>
<h3>Builder Templates</h3>

<p>The <tt>builder</tt> gem/library is required to render builder templates:</p>

<pre># You'll need to require builder in your app
require 'builder'

get '/' do
  builder :index

<p>Renders <tt>./views/index.builder</tt>.</p>

<a name='Nokogiri%20Templates'></a>
<h3>Nokogiri Templates</h3>

<p>The <tt>nokogiri</tt> gem/library is required to render nokogiri templates:</p>

<pre># You'll need to require nokogiri in your app
require 'nokogiri'

get '/' do
  nokogiri :index

<p>Renders <tt>./views/index.nokogiri</tt>.</p>

<a name='Sass%20Templates'></a>
<h3>Sass Templates</h3>

<p>The <tt>haml</tt> or <tt>sass</tt> gem/library is required to render Sass

<pre># You'll need to require haml or sass in your app
require 'sass'

get '/stylesheet.css' do
  sass :stylesheet

<p>Renders <tt>./views/stylesheet.sass</tt>.</p>

options</a> can be set globally through Sinatra’s configurations, see <a
href="">Options and
Configurations</a>, and overridden on an individual basis.</p>

<pre>set :sass, :style =&gt; :compact # default Sass style is :nested

get '/stylesheet.css' do
  sass :stylesheet, :style =&gt; :expanded # overridden

<a name='Scss%20Templates'></a>
<h3>Scss Templates</h3>

<p>The <tt>haml</tt> or <tt>sass</tt> gem/library is required to render Scss

<pre># You'll need to require haml or sass in your app
require 'sass'

get '/stylesheet.css' do
  scss :stylesheet

<p>Renders <tt>./views/stylesheet.scss</tt>.</p>

options</a> can be set globally through Sinatra’s configurations, see <a
href="">Options and
Configurations</a>, and overridden on an individual basis.</p>

<pre>set :scss, :style =&gt; :compact # default Scss style is :nested

get '/stylesheet.css' do
  scss :stylesheet, :style =&gt; :expanded # overridden

<a name='Less%20Templates'></a>
<h3>Less Templates</h3>

<p>The <tt>less</tt> gem/library is required to render Less templates:</p>

<pre># You'll need to require less in your app
require 'less'

get '/stylesheet.css' do
  less :stylesheet

<p>Renders <tt>./views/stylesheet.less</tt>.</p>

<a name='Liquid%20Templates'></a>
<h3>Liquid Templates</h3>

<p>The <tt>liquid</tt> gem/library is required to render Liquid templates:</p>

<pre># You'll need to require liquid in your app
require 'liquid'

get '/' do
  liquid :index

<p>Renders <tt>./views/index.liquid</tt>.</p>

<p>Since you cannot call Ruby methods (except for <tt>yield</tt>) from a
Liquid template, you almost always want to pass locals to it:</p>

<pre>liquid :index, :locals =&gt; { :key =&gt; 'value' }</pre>

<a name='Markdown%20Templates'></a>
<h3>Markdown Templates</h3>

<p>The <tt>rdiscount</tt> gem/library is required to render Markdown

<pre># You'll need to require rdiscount in your app
require &quot;rdiscount&quot;

get '/' do
  markdown :index

<p>Renders <tt>./views/index.markdown</tt> (<tt>md</tt> and <tt>mkd</tt> are
also valid file extensions).</p>

<p>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

<pre>erb :overview, :locals =&gt; { :text =&gt; markdown(:introduction) }</pre>

<p>Note that you may also call the <tt>markdown</tt> method from within other

<pre>%h1 Hello From Haml!
%p= markdown(:greetings)</pre>

<p>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 <tt>:layout_engine</tt> option:</p>

<pre>get '/' do
  markdown :index, :layout_engine =&gt; :erb

<p>This will render <tt>./views/</tt> with <tt>./views/layout.erb</tt>
as layout.</p>

<p>Remember that you can set such rendering options globally:</p>

<pre>set :markdown, :layout_engine =&gt; :haml, :layout =&gt; :post

get '/' do
  markdown :index

<p>This will render <tt>./views/</tt> (and any other Markdown
template) with <tt>./views/post.haml</tt> as layout.</p>

<p>It is also possible to parse Markdown with BlueCloth rather than RDiscount:</p>

<pre>require 'bluecloth'

Tilt.register 'markdown', BlueClothTemplate
Tilt.register 'mkd',      BlueClothTemplate
Tilt.register 'md',       BlueClothTemplate

get '/' do
  markdown :index

<p>Renders <tt>./views/</tt> with BlueCloth.</p>

<a name='Textile%20Templates'></a>
<h3>Textile Templates</h3>

<p>The <tt>RedCloth</tt> gem/library is required to render Textile templates:</p>

<pre># You'll need to require redcloth in your app
require &quot;redcloth&quot;

get '/' do
  textile :index

<p>Renders <tt>./views/index.textile</tt>.</p>

<p>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

<pre>erb :overview, :locals =&gt; { :text =&gt; textile(:introduction) }</pre>

<p>Note that you may also call the <tt>textile</tt> method from within other

<pre>%h1 Hello From Haml!
%p= textile(:greetings)</pre>

<p>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 <tt>:layout_engine</tt> option:</p>

<pre>get '/' do
  textile :index, :layout_engine =&gt; :erb

<p>This will render <tt>./views/index.textile</tt> with
<tt>./views/layout.erb</tt> as layout.</p>

<p>Remember that you can set such rendering options globally:</p>

<pre>set :textile, :layout_engine =&gt; :haml, :layout =&gt; :post

get '/' do
  textile :index

<p>This will render <tt>./views/index.textile</tt> (and any other Textile
template) with <tt>./views/post.haml</tt> as layout.</p>

<a name='RDoc%20Templates'></a>
<h3>RDoc Templates</h3>

<p>The <tt>rdoc</tt> gem/library is required to render RDoc templates:</p>

<pre># You'll need to require rdoc/markup/to_html in your app
require &quot;rdoc/markup/to_html&quot;

get '/' do
  rdoc :index

<p>Renders <tt>./views/index.rdoc</tt>.</p>

<p>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:</p>

<pre>erb :overview, :locals =&gt; { :text =&gt; rdoc(:introduction) }</pre>

<p>Note that you may also call the <tt>rdoc</tt> method from within other

<pre>%h1 Hello From Haml!
%p= rdoc(:greetings)</pre>

<p>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 <tt>:layout_engine</tt> option:</p>

<pre>get '/' do
  rdoc :index, :layout_engine =&gt; :erb

<p>This will render <tt>./views/index.rdoc</tt> with
<tt>./views/layout.erb</tt> as layout.</p>

<p>Remember that you can set such rendering options globally:</p>

<pre>set :rdoc, :layout_engine =&gt; :haml, :layout =&gt; :post

get '/' do
  rdoc :index

<p>This will render <tt>./views/index.rdoc</tt> (and any other RDoc template)
with <tt>./views/post.haml</tt> as layout.</p>

<a name='Radius%20Templates'></a>
<h3>Radius Templates</h3>

<p>The <tt>radius</tt> gem/library is required to render Radius templates:</p>

<pre># You'll need to require radius in your app
require 'radius'

get '/' do
  radius :index

<p>Renders <tt>./views/index.radius</tt>.</p>

<p>Since you cannot call Ruby methods (except for <tt>yield</tt>) from a
Radius template, you almost always want to pass locals to it:</p>

<pre>radius :index, :locals =&gt; { :key =&gt; 'value' }</pre>

<a name='Markaby%20Templates'></a>
<h3>Markaby Templates</h3>

<p>The <tt>markaby</tt> gem/library is required to render Markaby templates:</p>

<pre># You'll need to require markaby in your app
require 'markaby'

get '/' do
  markaby :index

<p>Renders <tt>./views/index.mab</tt>.</p>

<p>You may also use inline Markaby:</p>

<pre>get '/' do
  markaby { h1 &quot;Welcome!&quot; }

<a name='Slim%20Templates'></a>
<h3>Slim Templates</h3>

<p>The <tt>slim</tt> gem/library is required to render Slim templates:</p>

<pre># You'll need to require slim in your app
require 'slim'

get '/' do
  slim :index

<p>Renders <tt>./views/index.slim</tt>.</p>

<a name='CoffeeScript%20Templates'></a>
<h3>CoffeeScript Templates</h3>

<p>The <tt>coffee-script</tt> gem/library and at least <b>one</b> of the
following options to execute JavaScript:</p>
<p><tt>node</tt> (from Node.js) in your path</p>
<p>you must be running on OSX</p>
<p><tt>therubyracer</tt> gem/library</p>

<p>See <a
for an updated list of options.</p>

<p>Now you can render CoffeeScript templates:</p>

<pre># You'll need to require coffee-script in your app
require 'coffee-script'

get '/application.js' do
  coffee :application

<p>Renders <tt>./views/</tt>.</p>

<a name='Embedded%20Templates'></a>
<h3>Embedded Templates</h3>

<pre>get '/' do
  haml '%div.title Hello World'

<p>Renders the embedded template string.</p>

<a name='Accessing%20Variables%20in%20Templates'></a>
<h3>Accessing Variables in Templates</h3>

<p>Templates are evaluated within the same context as route handlers. Instance
variables set in route handlers are directly accessible by templates:</p>

<pre>get '/:id' do
  @foo = Foo.find(params[:id])
  haml '%h1='

<p>Or, specify an explicit Hash of local variables:</p>

<pre>get '/:id' do
  foo = Foo.find(params[:id])
  haml '%h1=', :locals =&gt; { :foo =&gt; foo }

<p>This is typically used when rendering templates as partials from within
other templates.</p>

<a name='Inline%20Templates'></a>
<h3>Inline Templates</h3>

<p>Templates may be defined at the end of the source file:</p>

<pre>require 'sinatra'

get '/' do
  haml :index


@@ layout
  = yield

@@ index
%div.title Hello world!!!!!</pre>

<p>NOTE: Inline templates defined in the source file that requires sinatra are
automatically loaded. Call <tt>enable :inline_templates</tt> explicitly if
you have inline templates in other source files.</p>

<a name='Named%20Templates'></a>
<h3>Named Templates</h3>

<p>Templates may also be defined using the top-level <tt>template</tt> method:</p>

<pre>template :layout do
  &quot;%html\n  =yield\n&quot;

template :index do
  '%div.title Hello World!'

get '/' do
  haml :index

<p>If a template named “layout” exists, it will be used each time a
template is rendered. You can individually disable layouts by passing
<tt>:layout =&gt; false</tt> or disable them by default via <tt>set :haml,
:layout =&gt; false</tt>.</p>

<pre>get '/' do
  haml :index, :layout =&gt; !request.xhr?

<a name='Associating%20File%20Extensions'></a>
<h3>Associating File Extensions</h3>

<p>To associate a file extension with a template engine, use
<tt>Tilt.register</tt>. For instance, if you like to use the file extension
<tt>tt</tt> for Textile templates, you can do the following:</p>

<pre>Tilt.register :tt, Tilt[:textile]</pre>

<a name='Adding%20Your%20Own%20Template%20Engine'></a>
<h3>Adding Your Own Template Engine</h3>

<p>First, register your engine with Tilt, then create a rendering method:</p>

<pre>Tilt.register :myat, MyAwesomeTemplateEngine

helpers do
  def myat(*args) render(:myat, *args) end

get '/' do
  myat :index

<p>Renders <tt>./views/index.myat</tt>. See <a
href=""></a> to
learn more about Tilt.</p>

<a name='Filters'></a>

<p>Before filters are evaluated before each request within the same context as
the routes will be and can modify the request and response. Instance
variables set in filters are accessible by routes and templates:</p>

<pre>before do
  @note = 'Hi!'
  request.path_info = '/foo/bar/baz'

get '/foo/*' do
  @note #=&gt; 'Hi!'
  params[:splat] #=&gt; 'bar/baz'

<p>After filters are evaluated after each request within the same context and
can also modify the request and response. Instance variables set in before
filters and routes are accessible by after filters:</p>

<pre>after do
  puts response.status

<p>Note: Unless you use the <tt>body</tt> method rather than just returning a
String from the routes, the body will not yet be available in the after
filter, since it is generated later on.</p>

<p>Filters optionally take a pattern, causing them to be evaluated only if the
request path matches that pattern:</p>

<pre>before '/protected/*' do

after '/create/:slug' do |slug|
  session[:last_slug] = slug

<p>Like routes, filters also take conditions:</p>

<pre>before :agent =&gt; /Songbird/ do
  # ...

after '/blog/*', :host_name =&gt; '' do
  # ...

<a name='Helpers'></a>

<p>Use the top-level <tt>helpers</tt> method to define helper methods for use
in route handlers and templates:</p>

<pre>helpers do
  def bar(name)

get '/:name' do

<a name='Using%20Sessions'></a>
<h3>Using Sessions</h3>

<p>A session is used to keep state during requests. If activated, you have one
session hash per user session:</p>

<pre>enable :sessions

get '/' do
  &quot;value = &quot; &lt;&lt; session[:value].inspect

get '/:value' do
  session[:value] = params[:value]

<p>Note that <tt>enable :sessions</tt> actually stores all data in a cookie.
This might not always be what you want (storing lots of data will increase
your traffic, for instance). You can use any Rack session middleware, in
order to do so, do <b>not</b> call <tt>enable :sessions</tt>, but instead
pull in your middleware of choice how you would any other middleware:</p>

<pre>use Rack::Session::Pool, :expire_after =&gt; 2592000

get '/' do
  &quot;value = &quot; &lt;&lt; session[:value].inspect

get '/:value' do
  session[:value] = params[:value]

<a name='Halting'></a>

<p>To immediately stop a request within a filter or route use:</p>


<p>You can also specify the status when halting:</p>

<pre>halt 410</pre>

<p>Or the body:</p>

<pre>halt 'this will be the body'</pre>

<p>Or both:</p>

<pre>halt 401, 'go away!'</pre>

<p>With headers:</p>

<pre>halt 402, {'Content-Type' =&gt; 'text/plain'}, 'revenge'</pre>

<p>It is of course possible to combine a template with <tt>halt</tt>:</p>

<pre>halt erb(:error)</pre>

<a name='Passing'></a>

<p>A route can punt processing to the next matching route using <tt>pass</tt>:</p>

<pre>get '/guess/:who' do
  pass unless params[:who] == 'Frank'
  'You got me!'

get '/guess/*' do
  'You missed!'

<p>The route block is immediately exited and control continues with the next
matching route. If no matching route is found, a 404 is returned.</p>

<a name='Triggering%20Another%20Route'></a>
<h3>Triggering Another Route</h3>

<p>Sometimes <tt>pass</tt> is not what you want, instead you would like to get
the result of calling another route. Simply use <tt>call</tt> to achieve

<pre>get '/foo' do
  status, headers, body = call request.env.merge(&quot;PATH_INFO&quot; =&gt; '/bar')
  [status, body.upcase]

get '/bar' do

<p>Note that in the example above, you would ease testing and increase
performance by simply moving <tt>&quot;bar&quot;</tt> into a helper used by
both <tt>/foo</tt> and <tt>/bar</tt>.</p>

<p>If you want the request to be sent to the same application instance rather
than a duplicate, use <tt>call!</tt> instead of <tt>call</tt>.</p>

<p>Check out the Rack specification if you want to learn more about

<a name='Setting%20Body,%20Status%20Code%20and%20Headers'></a>
<h3>Setting Body, Status Code and Headers</h3>

<p>It is possible and recommended to set the status code and response body
with the return value of the route block. However, in some scenarios you
might want to set the body at an arbitrary point in the execution flow. You
can do so with the <tt>body</tt> helper method. If you do so, you can use
that method from there on to access the body:</p>

<pre>get '/foo' do
  body &quot;bar&quot;

after do
  puts body

<p>It is also possible to pass a block to <tt>body</tt>, which will be
executed by the Rack handler (this can be used to implement streaming, see
“Return Values”).</p>

<p>Similar to the body, you can also set the status code and headers:</p>

<pre>get '/foo' do
  status 418
  headers \
    &quot;Allow&quot;   =&gt; &quot;BREW, POST, GET, PROPFIND, WHEN&quot;
    &quot;Refresh&quot; =&gt; &quot;Refresh: 20;;
  body &quot;I'm a tea pot!&quot;

<p>Like <tt>body</tt>, <tt>headers</tt> and <tt>status</tt> with no arguments
can be used to access their current values.</p>

<a name='Mime%20Types'></a>
<h3>Mime Types</h3>

<p>When using <tt>send_file</tt> or static files you may have mime types
Sinatra doesn’t understand. Use <tt>mime_type</tt> to register them by
file extension:</p>

<pre>mime_type :foo, 'text/foo'</pre>

<p>You can also use it with the <tt>content_type</tt> helper:</p>

<pre>get '/' do
  content_type :foo
  &quot;foo foo foo&quot;

<a name='Generating%20URLs'></a>
<h3>Generating URLs</h3>

<p>For generating URLs you should use the <tt>url</tt> helper method, for
instance, in Haml:</p>

<pre>%a{:href =&gt; url('/foo')} foo</pre>

<p>It takes reverse proxies and Rack routers into account, if present.</p>

<p>This method is also aliased to <tt>to</tt> (see below for an example).</p>

<a name='Browser%20Redirect'></a>
<h3>Browser Redirect</h3>

<p>You can trigger a browser redirect with the <tt>redirect</tt> helper

<pre>get '/foo' do
  redirect to('/bar')

<p>Any additional parameters are handled like arguments passed to

<pre>redirect to('/bar'), 303
redirect '', 'wrong place, buddy'</pre>

<p>You can also easily redirect back to the page the user came from with
<tt>redirect back</tt>:</p>

<pre>get '/foo' do
  &quot;&lt;a href='/bar'&gt;do something&lt;/a&gt;&quot;

get '/bar' do
  redirect back

<p>To pass arguments with a redirect, either add them to the query:</p>

<pre>redirect to('/bar?sum=42')</pre>

<p>Or use a session:</p>

<pre>enable :session

get '/foo' do
  session[:secret] = 'foo'
  redirect to('/bar')

get '/bar' do

<a name='Cache%20Control'></a>
<h3>Cache Control</h3>

<p>Setting your headers correctly is the foundation for proper HTTP caching.</p>

<p>You can easily set the Cache-Control header with like this:</p>

<pre>get '/' do
  cache_control :public
  &quot;cache it!&quot;

<p>Pro tip: Set up caching in a before filter.</p>

<pre>before do
  cache_control :public, :must_revalidate, :max_age =&gt; 60

<p>If you are using the <tt>expires</tt> helper to set the corresponding
header, <tt>Cache-Control</tt> will be set automatically for you:</p>

<pre>before do
  expires 500, :public, :must_revalidate

<p>To properly use caches, you should consider using <tt>etag</tt> and
<tt>last_modified</tt>. It is recommended to call those helpers
<b>before</b> doing heavy lifting, as they will immediately flush a
response if the client already has the current version in its cache.</p>

<pre>get '/article/:id' do
  @article = Article.find params[:id]
  last_modified @article.updated_at
  etag @article.sha1
  erb :article

<p>It is also possible to use a <a

<pre>etag @article.sha1, :weak</pre>

<p>These helpers will not do any caching for you, but rather feed the
necessary information to your cache. If you are looking for a quick caching
solutions, try <a

<pre>require &quot;rack/cache&quot;
require &quot;sinatra&quot;

use Rack::Cache

get '/' do
  cache_control :public, :max_age =&gt; 36000
  sleep 5

<a name='Sending%20Files'></a>
<h3>Sending Files</h3>

<p>For sending files, you can use the <tt>send_file</tt> helper method:</p>

<pre>get '/' do
  send_file 'foo.png'

<p>It also takes a couple of options:</p>

<pre>send_file 'foo.png', :type =&gt; :jpg</pre>

<p>The options are:</p>
<p>file name, in response, defaults to the real file name.</p>
<p>value for Last-Modified header, defaults to the file’s mtime.</p>
<p>content type to use, guessed from the file extension if missing.</p>
<p>used for Content-Disposition, possible values: <tt>nil</tt> (default),
<tt>:attachment</tt> and <tt>:inline</tt></p>
<p>Content-Length header, defaults to file size.</p>

<p>If supported by the Rack handler, other means than streaming from the Ruby
process will be used. If you use this helper method, Sinatra will
automatically handle range requests.</p>

<a name='Accessing%20the%20Request%20Object'></a>
<h3>Accessing the Request Object</h3>

<p>The incoming request object can be accessed from request level (filter,
routes, error handlers) through the <tt>request</tt> method:</p>

<pre># app running on
get '/foo' do
  request.body              # request body sent by the client (see below)
  request.scheme            # &quot;http&quot;
  request.script_name       # &quot;/example&quot;
  request.path_info         # &quot;/foo&quot;
  request.port              # 80
  request.request_method    # &quot;GET&quot;
  request.query_string      # &quot;&quot;
  request.content_length    # length of request.body
  request.media_type        # media type of request.body              # &quot;;
  request.get?              # true (similar methods for other verbs)
  request.form_data?        # false
  request[&quot;SOME_HEADER&quot;]    # value of SOME_HEADER header
  request.referrer          # the referrer of the client or '/'
  request.user_agent        # user agent (used by :agent condition)
  request.cookies           # hash of browser cookies
  request.xhr?              # is this an ajax request?
  request.url               # &quot;;
  request.path              # &quot;/example/foo&quot;
  request.ip                # client IP address           # false (would be true over ssl)
  request.forwarded?        # true (if running behind a reverse proxy)
  request.env               # raw env hash handed in by Rack

<p>Some options, like <tt>script_name</tt> or <tt>path_info</tt>, can also be

<pre>before { request.path_info = &quot;/&quot; }

get &quot;/&quot; do
  &quot;all requests end up here&quot;

<p>The <tt>request.body</tt> is an IO or StringIO object:</p>

<pre>post &quot;/api&quot; do
  request.body.rewind  # in case someone already read it
  data = JSON.parse
  &quot;Hello #{data['name']}!&quot;

<a name='Attachments'></a>

<p>You can use the <tt>attachment</tt> helper to tell the browser the response
should be stored on disk rather than displayed in the browser.</p>

<pre>get '/' do
  &quot;store it!&quot;

<p>You can also pass it a file name:</p>

<pre>get '/' do
  attachment &quot;info.txt&quot;
  &quot;store it!&quot;

<a name='Looking%20Up%20Template%20Files'></a>
<h3>Looking Up Template Files</h3>

<p>The <tt>find_template</tt> helper is used to find template files for

<pre>find_template settings.views, 'foo', Tilt[:haml] do |file|
  puts &quot;could be #{file}&quot;

<p>This is not really useful. But it is useful that you can actually override
this method to hook in your own lookup mechanism. For instance, if you want
to be able to use more than one view directory:</p>

<pre>set :views, ['views', 'templates']

helpers do
  def find_template(views, name, engine, &amp;block)
    Array(views).each { |v| super(v, name, engine, &amp;block) }

<p>Another example would be using different directories for different engines:</p>

<pre>set :views, :sass =&gt; 'views/sass', :haml =&gt; 'templates', :default =&gt; 'views'

helpers do
  def find_template(views, name, engine, &amp;block)
    _, folder = views.detect { |k,v| engine == Tilt[k] }
    folder ||= views[:default]
    super(folder, name, engine, &amp;block)

<p>You can also easily wrap this up in an extension and share with others!</p>

<p>Note that <tt>find_template</tt> does not check if the file really exists
but rather calls the given block for all possible paths. This is not a
performance issue, since <tt>render</tt> will use <tt>break</tt> as soon as
a file is found. Also, template locations (and content) will be cached if
you are not running in development mode. You should keep that in mind if
you write a really crazy method.</p>

<a name='Configuration'></a>

<p>Run once, at startup, in any environment:</p>

<pre>configure do
  # setting one option
  set :option, 'value'

  # setting multiple options
  set :a =&gt; 1, :b =&gt; 2

  # same as `set :option, true`
  enable :option

  # same as `set :option, false`
  disable :option

  # you can also have dynamic settings with blocks
  set(:css_dir) { File.join(views, 'css') }

<p>Run only when the environment (RACK_ENV environment variable) is set to

<pre>configure :production do

<p>Run when the environment is set to either <tt>:production</tt> or

<pre>configure :production, :test do

<p>You can access those options via <tt>settings</tt>:</p>

<pre>configure do
  set :foo, 'bar'

get '/' do # =&gt; true  # =&gt; 'bar'

<a name='Available%20Settings'></a>
<h3>Available Settings</h3>
<p>If disabled, Sinatra will allow relative redirects, however, Sinatra will
no longer conform with RFC 2616 (HTTP 1.1), which only allows absolute

<p>Enable if your app is running behind a reverse proxy that has not been set
up properly. Note that the <tt>url</tt> helper will still produce absolute
URLs, unless you pass in <tt>false</tt> as second parameter.</p>

<p>Disabled per default.</p>
<p>mime types the <tt>content_type</tt> helper will automatically add the
charset info to.</p>

<p>You should add to it rather than overriding this option:</p>

<pre>settings.add_charsets &lt;&lt; &quot;application/foobar&quot;</pre>
<p>main application file, used to detect project root, views and public folder
and inline templates.</p>
<p>IP address to bind to (default: Only used for built-in server.</p>
<p>encoding to assume if unknown (defaults to <tt>&quot;utf-8&quot;</tt>).</p>
<p>display errors in the log.</p>
<p>current environment, defaults to <tt>ENV['RACK_ENV']</tt>, or
<tt>&quot;development&quot;</tt> if not available.</p>
<p>use the logger.</p>
<p>Places a lock around every request, only running processing on request per
Ruby process concurrently.</p>

<p>Enabled if your app is not thread-safe. Disabled per default.</p>
<p>use <tt>_method</tt> magic to allow put/delete forms in browsers that
don’t support it.</p>
<p>Port to listen on. Only used for built-in server.</p>
<p>Whether or not to insert <tt>request.script_name</tt> into redirects if no
absolute path is given. That way <tt>redirect '/foo'</tt> would behave like
<tt>redirect to('/foo')</tt>. Disabled per default.</p>
<p>folder public files are served from</p>
<p>whether or not to reload templates between requests. Enabled in development
mode and on Ruby 1.8.6 (to compensate a bug in Ruby causing a memory leak).</p>
<p>project root folder.</p>
<p>raise exceptions (will stop application).</p>
<p>if enabled, Sinatra will handle starting the web server, do not enable if
using rackup or other means.</p>
<p>is the built-in server running now? do not change this setting!</p>
<p>server or list of servers to use for built-in server. defaults to
[‘thin’, ‘mongrel’, ‘webrick’], order indicates priority.</p>
<p>enable cookie based sessions.</p>
<p>show a stack trace in the browser.</p>
<p>Whether Sinatra should handle serving static files. Disable when using a
Server able to do this on its own. Disabling will boost performance.
Enabled per default.</p>
<p>views folder.</p>

<a name='Error%20Handling'></a>
<h2>Error Handling</h2>

<p>Error handlers run within the same context as routes and before filters,
which means you get all the goodies it has to offer, like <tt>haml</tt>,
<tt>erb</tt>, <tt>halt</tt>, etc.</p>

<a name='Not%20Found'></a>
<h3>Not Found</h3>

<p>When a <tt>Sinatra::NotFound</tt> exception is raised, or the response’s
status code is 404, the <tt>not_found</tt> handler is invoked:</p>

<pre>not_found do
  'This is nowhere to be found.'

<a name='Error'></a>

<p>The <tt>error</tt> handler is invoked any time an exception is raised from
a route block or a filter. The exception object can be obtained from the
<tt>sinatra.error</tt> Rack variable:</p>

<pre>error do
  'Sorry there was a nasty error - ' + env['sinatra.error'].name

<p>Custom errors:</p>

<pre>error MyCustomError do
  'So what happened was...' + request.env['sinatra.error'].message

<p>Then, if this happens:</p>

<pre>get '/' do
  raise MyCustomError, 'something bad'

<p>You get this:</p>

<pre>So what happened was... something bad</pre>

<p>Alternatively, you can install an error handler for a status code:</p>

<pre>error 403 do
  'Access forbidden'

get '/secret' do

<p>Or a range:</p>

<pre>error 400..510 do

<p>Sinatra installs special <tt>not_found</tt> and <tt>error</tt> handlers
when running under the development environment.</p>

<a name='Rack%20Middleware'></a>
<h2>Rack Middleware</h2>

<p>Sinatra rides on <a href="">Rack</a>, a minimal
standard interface for Ruby web frameworks. One of Rack’s most
interesting capabilities for application developers is support for
“middleware” – components that sit between the server and your
application monitoring and/or manipulating the HTTP request/response to
provide various types of common functionality.</p>

<p>Sinatra makes building Rack middleware pipelines a cinch via a top-level
<tt>use</tt> method:</p>

<pre>require 'sinatra'
require 'my_custom_middleware'

use Rack::Lint
use MyCustomMiddleware

get '/hello' do
  'Hello World'

<p>The semantics of <tt>use</tt> are identical to those defined for the <a
DSL (most frequently used from rackup files). For example, the <tt>use</tt>
method accepts multiple/variable args as well as blocks:</p>

<pre>use Rack::Auth::Basic do |username, password|
  username == 'admin' &amp;&amp; password == 'secret'

<p>Rack is distributed with a variety of standard middleware for logging,
debugging, URL routing, authentication, and session handling. Sinatra uses
many of these components automatically based on configuration so you
typically don’t have to <tt>use</tt> them explicitly.</p>

<a name='Testing'></a>

<p>Sinatra tests can be written using any Rack-based testing library or
framework. <a href="">Rack::Test</a> is

<pre>require 'my_sinatra_app'
require 'test/unit'
require 'rack/test'

class MyAppTest &lt; Test::Unit::TestCase
  include Rack::Test::Methods

  def app

  def test_my_default
    get '/'
    assert_equal 'Hello World!', last_response.body

  def test_with_params
    get '/meet', :name =&gt; 'Frank'
    assert_equal 'Hello Frank!', last_response.body

  def test_with_rack_env
    get '/', {}, 'HTTP_USER_AGENT' =&gt; 'Songbird'
    assert_equal &quot;You're using Songbird!&quot;, last_response.body

<p>NOTE: The built-in Sinatra::Test module and Sinatra::TestHarness class are
deprecated as of the 0.9.2 release.</p>

<a name='Sinatra::Base%20-%20Middleware,%20Libraries,%20and%20Modular%20Apps'></a>
<h2>Sinatra::Base - Middleware, Libraries, and Modular Apps</h2>

<p>Defining your app at the top-level works well for micro-apps but has
considerable drawbacks when building reusable components such as Rack
middleware, Rails metal, simple libraries with a server component, or even
Sinatra extensions. The top-level DSL pollutes the Object namespace and
assumes a micro-app style configuration (e.g., a single application file,
./public and ./views directories, logging, exception detail page, etc.).
That’s where Sinatra::Base comes into play:</p>

<pre>require 'sinatra/base'

class MyApp &lt; Sinatra::Base
  set :sessions, true
  set :foo, 'bar'

  get '/' do
    'Hello world!'

<p>The methods available to Sinatra::Base subclasses are exactly as those
available via the top-level DSL. Most top-level apps can be converted to
Sinatra::Base components with two modifications:</p>
<p>Your file should require <tt>sinatra/base</tt> instead of <tt>sinatra</tt>;
otherwise, all of Sinatra’s DSL methods are imported into the main
<p>Put your app’s routes, error handlers, filters, and options in a subclass
of Sinatra::Base.</p>

<p><tt>Sinatra::Base</tt> is a blank slate. Most options are disabled by
default, including the built-in server. See <a
href="">Options and
Configuration</a> for details on available options and their behavior.</p>

<a name='Modular%20vs.%20Classic%20Style'></a>
<h3>Modular vs. Classic Style</h3>

<p>Contrary to common belief, there is nothing wrong with classic style. If it
suits your application, you do not have to switch to a modular application.</p>

<p>There are only two downsides compared with modular style:</p>
<p>You may only have one Sinatra application per Ruby process. If you plan to
use more, switch to modular style.</p>
<p>Classic style pollutes Object with delegator methods. If you plan to ship
your application in a library/gem, switch to modular style.</p>

<p>There is no reason you cannot mix modular and classic style.</p>

<p>If switching from one style to the other, you should be aware of slight
differences in the setting:</p>

<pre>Setting             Classic                 Modular

app_file            file loading sinatra    nil
run                 $0 == app_file          false
logging             true                    false
method_override     true                    false
inline_templates    true                    false</pre>

<a name='Serving%20a%20Modular%20Application'></a>
<h3>Serving a Modular Application</h3>

<p>There are two common options for starting a modular app, actively starting
with <tt>run!</tt>:</p>

<pre># my_app.rb
require 'sinatra/base'

class MyApp &lt; Sinatra::Base
  # ... app code here ...

  # start the server if ruby file executed directly
  run! if app_file == $0

<p>Start with:</p>

<pre>ruby my_app.rb</pre>

<p>Or with a <tt></tt>, which allows using any Rack handler:</p>

require 'my_app'
run MyApp</pre>


<pre>rackup -p 4567</pre>

<a name=''></a>
<h3>Using a Classic Style Application with a</h3>

<p>Write your app file:</p>

<pre># app.rb
require 'sinatra'

get '/' do
  'Hello world!'

<p>And a corresponding <tt></tt>:</p>

<pre>require 'app'
run Sinatra::Application</pre>

<a name=''></a>
<h3>When to use a</h3>

<p>Good signs you probably want to use a <tt></tt>:</p>
<p>You want to deploy with a different Rack handler (Passenger, Unicorn,
Heroku, …).</p>
<p>You want to use more than one subclass of <tt>Sinatra::Base</tt>.</p>
<p>You want to use Sinatra only for middleware, but not as endpoint.</p>

<p><b>There is no need to switch to a <tt></tt> only because you
switched to modular style, and you don’t have to use modular style for
running with a <tt></tt>.</b></p>

<a name='Using%20Sinatra%20as%20Middleware'></a>
<h3>Using Sinatra as Middleware</h3>

<p>Not only is Sinatra able to use other Rack middleware, any Sinatra
application can in turn be added in front of any Rack endpoint as
middleware itself. This endpoint could be another Sinatra application, or
any other Rack-based application (Rails/Ramaze/Camping/…).</p>

<pre>require 'sinatra/base'

class LoginScreen &lt; Sinatra::Base
  enable :sessions

  get('/login') { haml :login }

  post('/login') do
    if params[:name] = 'admin' and params[:password] = 'admin'
      session['user_name'] = params[:name]
      redirect '/login'

class MyApp &lt; Sinatra::Base
  # middleware will run before filters
  use LoginScreen

  before do
    unless session['user_name']
      halt &quot;Access denied, please &lt;a href='/login'&gt;login&lt;/a&gt;.&quot;

  get('/') { &quot;Hello #{session['user_name']}.&quot; }

<a name='Scopes%20and%20Binding'></a>
<h2>Scopes and Binding</h2>

<p>The scope you are currently in determines what methods and variables are

<a name='Application/Class%20Scope'></a>
<h3>Application/Class Scope</h3>

<p>Every Sinatra application corresponds to a subclass of Sinatra::Base. If
you are using the top-level DSL (<tt>require 'sinatra'</tt>), then this
class is Sinatra::Application, otherwise it is the subclass you created
explicitly. At class level you have methods like <tt>get</tt> or
<tt>before</tt>, but you cannot access the <tt>request</tt> object or the
<tt>session</tt>, as there only is a single application class for all

<p>Options created via <tt>set</tt> are methods at class level:</p>

<pre>class MyApp &lt; Sinatra::Base
  # Hey, I'm in the application scope!
  set :foo, 42
  foo # =&gt; 42

  get '/foo' do
    # Hey, I'm no longer in the application scope!

<p>You have the application scope binding inside:</p>
<p>Your application class body</p>
<p>Methods defined by extensions</p>
<p>The block passed to <tt>helpers</tt></p>
<p>Procs/blocks used as value for <tt>set</tt></p>

<p>You can reach the scope object (the class) like this:</p>
<p>Via the object passed to configure blocks (<tt>configure { |c| ... }</tt>)</p>
<p><tt>settings</tt> from within request scope</p>

<a name='Request/Instance%20Scope'></a>
<h3>Request/Instance Scope</h3>

<p>For every incoming request, a new instance of your application class is
created and all handler blocks run in that scope. From within this scope
you can access the <tt>request</tt> and <tt>session</tt> object or call
rendering methods like <tt>erb</tt> or <tt>haml</tt>. You can access the
application scope from within the request scope via the <tt>settings</tt>

<pre>class MyApp &lt; Sinatra::Base
  # Hey, I'm in the application scope!
  get '/define_route/:name' do
    # Request scope for '/define_route/:name'
    @value = 42

    settings.get(&quot;/#{params[:name]}&quot;) do
      # Request scope for &quot;/#{params[:name]}&quot;
      @value # =&gt; nil (not the same request)

    &quot;Route defined!&quot;

<p>You have the request scope binding inside:</p>
<p>get/head/post/put/delete/options blocks</p>
<p>before/after filters</p>
<p>helper methods</p>

<a name='Delegation%20Scope'></a>
<h3>Delegation Scope</h3>

<p>The delegation scope just forwards methods to the class scope. However, it
does not behave 100% like the class scope, as you do not have the class
binding. Only methods explicitly marked for delegation are available and
you do not share variables/state with the class scope (read: you have a
different <tt>self</tt>). You can explicitly add method delegations by
calling <tt>Sinatra::Delegator.delegate :method_name</tt>.</p>

<p>You have the delegate scope binding inside:</p>
<p>The top level binding, if you did <tt>require &quot;sinatra&quot;</tt></p>
<p>An object extended with the <tt>Sinatra::Delegator</tt> mixin</p>

<p>Have a look at the code for yourself: here’s the <a
mixin</a> being <a
into the main namespace</a>.</p>

<a name='Command%20Line'></a>
<h2>Command Line</h2>

<p>Sinatra applications can be run directly:</p>

<pre>ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER]</pre>

<p>Options are:</p>

<pre>-h # help
-p # set the port (default is 4567)
-o # set the host (default is
-e # set the environment (default is development)
-s # specify rack server/handler (default is thin)
-x # turn on the mutex lock (default is off)</pre>

<a name='Requirements'></a>

<p>It is recommended to install Sinatra on Ruby 1.8.7, 1.9.2, JRuby or

<p>The following Ruby versions are officially supported:</p>
<dl><dt> Ruby 1.8.6 </dt>
<p>It is not recommended to use 1.8.6 for Sinatra. However, it will be
officially supported until Sinatra 1.3.0 is released. RDoc and CoffeScript
templates are not supported by this Ruby version. 1.8.6 includes a major
memory leak in its Hash implementation, which is triggered by Sinatra
versions prior to 1.1.1. The current version explicitly prevents this leak
at the cost of performance. You will have to downgrade Rack to 1.1.x, as
Rack &gt;= 1.2 no longer supports 1.8.6.</p>
</dd><dt> Ruby 1.8.7 </dt>
<p>1.8.7 is fully supported, however, if nothing is keeping you from it, we
recommend upgrading to 1.9.2 or switching to JRuby or Rubinius.</p>
</dd><dt> Ruby 1.9.2 </dt>
<p>1.9.2 is supported and recommended. Note that Radius and Markaby are
currently not 1.9 compatible. Do not use 1.9.2p0, it is known to cause
segmentation faults when using Sinatra.</p>
</dd><dt> Rubinius </dt>
<p>Rubinius is officially supported (Rubinius &gt;= 1.2.2), with the exception
of Textile templates.</p>
</dd><dt> JRuby </dt>
<p>JRuby is officially supported (JRuby &gt;= 1.5.6). No issues with third
party template libraries are known, however, if you choose to use JRuby,
please look into JRuby rack handlers, as the Thin web server is not (yet)
supported on JRuby.</p>

<p>We also keep an eye on upcoming Ruby versions.</p>

<p>The following Ruby implementations are not officially supported but still
are known to run Sinatra:</p>
<p>Older versions of JRuby and Rubinius</p>
<p>Ruby 1.9.0 and 1.9.1</p>

<p>Not being officially supported means if things only break there and not on
a supported platform, we assume it’s not our issue but theirs.</p>

<p>Sinatra should work on any operating system supported by the chosen Ruby

<a name='The%20Bleeding%20Edge'></a>
<h2>The Bleeding Edge</h2>

<p>If you would like to use Sinatra’s latest bleeding code, feel free to run
your application against the master branch, it should be rather stable.</p>

<p>We also push out prerelease gems from time to time, so you can do a</p>

<pre>gem install sinatra --pre</pre>

<p>To get some of the latest features.</p>

<a name='With%20Bundler'></a>
<h3>With Bundler</h3>

<p>If you want to run your application with the latest Sinatra, using <a
href="">Bundler</a> is the recommended way.</p>

<p>First, install bundler, if you haven’t:</p>

<pre>gem install bundler</pre>

<p>Then, in your project directory, create a <tt>Gemfile</tt>:</p>

<pre>source :rubygems
gem 'sinatra', :git =&gt; &quot;git://;

# other dependencies
gem 'haml'                    # for instance, if you use haml
gem 'activerecord', '~&gt; 3.0'  # maybe you also need ActiveRecord 3.x</pre>

<p>Note that you will have to list all your applications dependencies in
there. Sinatra’s direct dependencies (Rack and Tilt) will, however, be
automatically fetched and added by Bundler.</p>

<p>Now you can run your app like this:</p>

<pre>bundle exec ruby myapp.rb</pre>

<a name='Roll%20Your%20Own'></a>
<h3>Roll Your Own</h3>

<p>Create a local clone and run your app with the <tt>sinatra/lib</tt>
directory on the <tt>$LOAD_PATH</tt>:</p>

<pre>cd myapp
git clone git://
ruby -Isinatra/lib myapp.rb</pre>

<p>To update the Sinatra sources in the future:</p>

<pre>cd myapp/sinatra
git pull</pre>

<a name='Install%20Globally'></a>
<h3>Install Globally</h3>

<p>You can build the gem on your own:</p>

<pre>git clone git://
cd sinatra
rake sinatra.gemspec
rake install</pre>

<p>If you install gems as root, the last step should be</p>

<pre>sudo rake install</pre>

<a name='Further%20Reading'></a>
<h2>Further Reading</h2>
<p><a href="">Project Website</a> - Additional
documentation, news, and links to other resources.</p>
<p><a href="">Contributing</a> - Find a
bug? Need help? Have a patch?</p>
<p><a href="">Issue tracker</a></p>
<p><a href="">Twitter</a></p>
<p><a href="">Mailing List</a></p>
<p><a href="irc://">IRC: #sinatra</a> on <a