Switch branches/tags
Nothing to show
Find file History
Pull request Compare This branch is 540 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='#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='#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%20You%20Own%20Template%20Engine'>Adding You Own Template Engine</a></li>
		<li><a href='#Helpers'>Helpers</a></li>
		<li><a href='#Filters'>Filters</a></li>
		<li><a href='#Halting'>Halting</a></li>
		<li><a href='#Passing'>Passing</a></li>
		<li><a href='#Accessing%20the%20Request%20Object'>Accessing the Request Object</a></li>
		<li><a href='#Configuration'>Configuration</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='#Mime%20Types'>Mime Types</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='#Serving%20a%20Modular%20Application'>Serving a Modular Application</a></li>
			<li><a href='#Using%20a%20Classic%20Style%20Application%20with%20a%20config.ru'>Using a Classic Style Application with a config.ru</a></li>
			<li><a href='#When%20to%20use%20a%20config.ru?'>When to use a config.ru?</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='#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>

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

<p>In Sinatra, a route is an HTTP method paired with an 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 ..

<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('/') { Stream.new }</pre>

<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="http://www.sinatrarb.com/configuration.html">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="http://www.sinatrarb.com/configuration.html">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="http://www.sinatrarb.com/configuration.html">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>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/index.md</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>

<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 in your app
require &quot;rdoc&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>

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

<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/application.coffee</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 direcly accessible by templates:</p>

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

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

<pre>get '/:id' do
  foo = Foo.find(params[:id])
  haml '%h1= foo.name', :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%20You%20Own%20Template%20Engine'></a>
<h3>Adding You 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="https://github.com/rtomayko/tilt">github.com/rtomayko/tilt</a> to
learn more about Tilt.</p>

<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='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 filter 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>Filters optionally taking 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

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

<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='Accessing%20the%20Request%20Object'></a>
<h2>Accessing the Request Object</h2>

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

<pre># app running on http://example.com/example
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
  request.host              # &quot;example.com&quot;
  request.get?              # true (similar methods for other verbs)
  request.form_data?        # false
  request[&quot;SOME_HEADER&quot;]    # value of SOME_HEADER header
  request.referer           # the referer 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;http://example.com/example/foo&quot;
  request.path              # &quot;/example/foo&quot;
  request.ip                # client IP address
  request.secure?           # false
  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 request.body.read
  &quot;Hello #{data['name']}!&quot;

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

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

<pre>configure do

<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

<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 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='Mime%20Types'></a>
<h2>Mime Types</h2>

<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>content_type :foo</pre>

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

<p>Sinatra rides on <a href="http://rack.rubyforge.org/">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 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="http://gitrdoc.com/brynary/rack-test">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 namespace.</p>
<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="http://sinatra.github.com/configuration.html">Options and
Configuration</a> for details on available options and their behavior.</p>

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

<p>There are two common options for starting a modular app, activly 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>config.ru</tt>, which allows using any Rack handler:</p>

<pre># config.ru
require 'my_app'
run MyApp</pre>


<pre>rackup -p 4567</pre>

<a name='Using%20a%20Classic%20Style%20Application%20with%20a%20config.ru'></a>
<h3>Using a Classic Style Application with a config.ru</h3>

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

<pre># app.rb
require 'sinatra'

get '/' do
  'Hello world!'

<p>And a corresponding <tt>config.ru</tt>:</p>

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

<a name='When%20to%20use%20a%20config.ru?'></a>
<h3>When to use a config.ru?</h3>

<p>Good signs you probably want to use a <tt>config.ru</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>config.ru</tt> only because you
switched to modular style, and you don’t have to use modular style for
running with a <tt>config.ru</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 `get` or `before`, but you
cannot access the `request` object or the `session`, as there only is a
single application class for all requests.</p>

<p>Options created via `set` 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 `helpers`</p>
<p>Procs/blocks used as value for `set`</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>`settings` 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 `request` and `session` object or call rendering methods
like `erb` or `haml`. You can access the application scope from within the
request scope via the `settings` helper:</p>

<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 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 `self`). 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 `Sinatra::Delegator` 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='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="http://gembundler.com/">Bundler</a> is the recommend way.</p>

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

<pre>gem install bundler</pre>

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

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

# 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://github.com/sinatra/sinatra.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://github.com/sinatra/sinatra.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="http://www.sinatrarb.com/">Project Website</a> - Additional
documentation, news, and links to other resources.</p>
<p><a href="http://www.sinatrarb.com/contributing">Contributing</a> - Find a
bug? Need help? Have a patch?</p>
<p><a href="http://github.com/sinatra/sinatra/issues">Issue tracker</a></p>
<p><a href="http://twitter.com/sinatra">Twitter</a></p>
<p><a href="http://groups.google.com/group/sinatrarb/topics">Mailing List</a></p>
<p><a href="irc://chat.freenode.net/#sinatra">IRC: #sinatra</a> on <a