Switch branches/tags
Nothing to show
Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
..
Failed to load latest commit information.
README.de.html
README.es.html
README.fr.html
README.html
README.hu.html
README.ja.html
README.ko.html
README.pt-br.html
README.pt-pt.html
README.ru.html
README.zh.html
head.html
navbar.html
rack-protection-authenticity-token.html
rack-protection-content-security-policy.html
rack-protection-cookie-tossing.html
rack-protection-escaped-params.html
rack-protection-form-token.html
rack-protection-frame-options.html
rack-protection-http-origin.html
rack-protection-ip-spoofing.html
rack-protection-json-csrf.html
rack-protection-path-traversal.html
rack-protection-readme.html
rack-protection-remote-referrer.html
rack-protection-remote-token.html
rack-protection-session-hijacking.html
rack-protection-strict-transport.html
rack-protection-xss-header.html
sinatra-capture.html
sinatra-config-file.html
sinatra-content-for.html
sinatra-contrib-readme.html
sinatra-cookies.html
sinatra-custom-logger.html
sinatra-engine-tracking.html
sinatra-extension.html
sinatra-json.html
sinatra-link-header.html
sinatra-multi-route.html
sinatra-namespace.html
sinatra-reloader.html
sinatra-required-params.html
sinatra-respond-with.html
sinatra-runner.html
sinatra-streaming.html
sinatra-test-helpers.html
sinatra-webdav.html

README.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>

<p><a href="http://travis-ci.org/sinatra/sinatra"><img src="https://secure.travis-ci.org/sinatra/sinatra.svg" alt="Build Status"></a></p>

<p>Sinatra is a <a href="https://en.wikipedia.org/wiki/Domain-specific_language">DSL</a> for
quickly creating web applications in Ruby with minimal effort:</p>

<pre><code class="language-ruby"># myapp.rb
require 'sinatra'

get '/' do
  'Hello world!'
end
</code></pre>

<p>Install the gem:</p>

<pre><code class="language-shell">gem install sinatra
</code></pre>

<p>And run with:</p>

<pre><code class="language-shell">ruby myapp.rb
</code></pre>

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

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





<h2>Routes</h2>

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

<pre><code class="language-ruby">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

link '/' do
  .. affiliate something ..
end

unlink '/' do
  .. separate something ..
end
</code></pre>

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

<p>Routes with trailing slashes are different from the ones without:</p>

<pre><code class="language-ruby">get '/foo' do
  # Does not match "GET /foo/"
end
</code></pre>

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

<pre><code class="language-ruby">get '/hello/:name' do
  # matches "GET /hello/foo" and "GET /hello/bar"
  # params['name'] is 'foo' or 'bar'
  "Hello #{params['name']}!"
end
</code></pre>

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

<pre><code class="language-ruby">get '/hello/:name' do |n|
  # matches "GET /hello/foo" and "GET /hello/bar"
  # params['name'] is 'foo' or 'bar'
  # n stores params['name']
  "Hello #{n}!"
end
</code></pre>

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

<pre><code class="language-ruby">get '/say/*/to/*' do
  # matches /say/hello/to/world
  params['splat'] # =&gt; ["hello", "world"]
end

get '/download/*.*' do
  # matches /download/path/to/file.xml
  params['splat'] # =&gt; ["path/to/file", "xml"]
end
</code></pre>

<p>Or with block parameters:</p>

<pre><code class="language-ruby">get '/download/*.*' do |path, ext|
  [path, ext] # =&gt; ["path/to/file", "xml"]
end
</code></pre>

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

<pre><code class="language-ruby">get /\/hello\/([\w]+)/ do
  "Hello, #{params['captures'].first}!"
end
</code></pre>

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

<pre><code class="language-ruby">get %r{/hello/([\w]+)} do |c|
  # Matches "GET /meta/hello/world", "GET /hello/world/1234" etc.
  "Hello, #{c}!"
end
</code></pre>

<p>Route patterns may have optional parameters:</p>

<pre><code class="language-ruby">get '/posts/:format?' do
  # matches "GET /posts/" and any extension "GET /posts/json", "GET /posts/xml" etc
end
</code></pre>

<p>Routes may also utilize query parameters:</p>

<pre><code class="language-ruby">get '/posts' do
  # matches "GET /posts?title=foo&amp;author=bar"
  title = params['title']
  author = params['author']
  # uses title and author variables; query is optional to the /posts route
end
</code></pre>

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

<p>You may customize the Mustermann options used for a given route by passing in a
<code>:mustermann_opts</code> hash:</p>

<pre><code class="language-ruby">get '\A/posts\z', :mustermann_opts =&gt; { :type =&gt; :regexp, :check_anchors =&gt; false } do
  # matches /posts exactly, with explicit anchoring
  "If you match an anchored pattern clap your hands!"
end
</code></pre>

<p>It looks like a <a href="#conditions">condition</a>, but it isn’t one! These options will
be merged into the global <code>:mustermann_opts</code> hash described
<a href="#available-settings">below</a>.</p>

<h2>Conditions</h2>

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

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

get '/foo' do
  # Matches non-songbird browsers
end
</code></pre>

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

<pre><code class="language-ruby">get '/', :host_name =&gt; /^admin\./ do
  "Admin Area, Access denied!"
end

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

get '/', :provides =&gt; ['rss', 'atom', 'xml'] do
  builder :feed
end
</code></pre>
<p><code>provides</code> searches the request’s Accept header.</p>

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

<pre><code class="language-ruby">set(:probability) { |value| condition { rand &lt;= value } }

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

get '/win_a_car' do
  "Sorry, you lost."
end
</code></pre>

<p>For a condition that takes multiple values use a splat:</p>

<pre><code class="language-ruby">set(:auth) do |*roles|   # &lt;- notice the splat here
  condition do
    unless logged_in? &amp;&amp; roles.any? {|role| current_user.in_role? role }
      redirect "/login/", 303
    end
  end
end

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

get "/only/admin/", :auth =&gt; :admin do
  "Only admins are allowed here!"
end
</code></pre>

<h2>Return Values</h2>

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

<ul>
  <li>An Array with three elements: <code>[status (Fixnum), headers (Hash), response
body (responds to #each)]</code>
</li>
  <li>An Array with two elements: <code>[status (Fixnum), response body (responds to
#each)]</code>
</li>
  <li>An object that responds to <code>#each</code> and passes nothing but strings to
the given block</li>
  <li>A Fixnum representing the status code</li>
</ul>

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

<pre><code class="language-ruby">class Stream
  def each
    100.times { |i| yield "#{i}\n" }
  end
end

get('/') { Stream.new }
</code></pre>

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

<h2>Custom Route Matchers</h2>

<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><code class="language-ruby">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
</code></pre>

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

<pre><code class="language-ruby">get // do
  pass if request.path_info == "/index"
  # ...
end
</code></pre>

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

<pre><code class="language-ruby">get %r{(?!/index)} do
  # ...
end
</code></pre>

<h2>Static Files</h2>

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

<pre><code class="language-ruby">set :public_folder, File.dirname(__FILE__) + '/static'
</code></pre>

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

<p>Use the <code>:static_cache_control</code> setting (see below) to add
<code>Cache-Control</code> header info.</p>

<h2>Views / Templates</h2>

<p>Each template language is exposed via its own rendering method. These
methods simply return a string:</p>

<pre><code class="language-ruby">get '/' do
  erb :index
end
</code></pre>

<p>This renders <code>views/index.erb</code>.</p>

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

<pre><code class="language-ruby">get '/' do
  code = "&lt;%= Time.now %&gt;"
  erb code
end
</code></pre>

<p>Templates take a second argument, the options hash:</p>

<pre><code class="language-ruby">get '/' do
  erb :index, :layout =&gt; :post
end
</code></pre>

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

<p>Any options not understood by Sinatra will be passed on to the template
engine:</p>

<pre><code class="language-ruby">get '/' do
  haml :index, :format =&gt; :html5
end
</code></pre>

<p>You can also set options per template language in general:</p>

<pre><code class="language-ruby">set :haml, :format =&gt; :html5

get '/' do
  haml :index
end
</code></pre>

<p>Options passed to the render method override options set via <code>set</code>.</p>

<p>Available Options:</p>

<dl>
  <dt>locals</dt>
  <dd>
    List of locals passed to the document. Handy with partials.
    Example: <tt>erb "&lt;%= foo %&gt;", :locals =&gt; {:foo =&gt; "bar"}</tt>
  </dd>

  <dt>default_encoding</dt>
  <dd>
    String encoding to use if uncertain. Defaults to
    <tt>settings.default_encoding</tt>.
  </dd>

  <dt>views</dt>
  <dd>
    Views folder to load templates from. Defaults to <tt>settings.views</tt>.
  </dd>

  <dt>layout</dt>
  <dd>
    Whether to use a layout (<tt>true</tt> or <tt>false</tt>). If it's a
    Symbol, specifies what template to use. Example:
    <tt>erb :index, :layout =&gt; !request.xhr?</tt>
  </dd>

  <dt>content_type</dt>
  <dd>
    Content-Type the template produces. Default depends on template language.
  </dd>

  <dt>scope</dt>
  <dd>
    Scope to render template under. Defaults to the application
    instance. If you change this, instance variables and helper methods
    will not be available.
  </dd>

  <dt>layout_engine</dt>
  <dd>
    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: <tt>set :rdoc, :layout_engine
    =&gt; :erb</tt>
  </dd>

  <dt>layout_options</dt>
  <dd>
    Special options only used for rendering the layout. Example:
    <tt>set :rdoc, :layout_options =&gt; { :views =&gt; 'views/layouts' }</tt>
  </dd>
</dl>

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

<pre><code class="language-ruby">set :views, settings.root + '/templates'
</code></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: <code>:'subdir/template'</code> or <code>'subdir/template'.to_sym</code>). You must use a
symbol because otherwise rendering methods will render any strings
passed to them directly.</p>

<h3>Literal Templates</h3>

<pre><code class="language-ruby">get '/' do
  haml '%div.title Hello World'
end
</code></pre>

<p>Renders the template string. You can optionally specify <code>:path</code> and
<code>:line</code> for a clearer backtrace if there is a filesystem path or line
associated with that string:</p>

<pre><code class="language-ruby">get '/' do
  haml '%div.title Hello World', :path =&gt; 'examples/file.haml', :line =&gt; 3
end
</code></pre>

<h3>Available Template Languages</h3>

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

<pre><code class="language-ruby">require 'rdiscount' # or require 'bluecloth'
get('/') { markdown :index }
</code></pre>

<h4>Haml Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="http://haml.info/" title="haml">haml</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.haml</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>haml :index, :format =&gt; :html5</tt></td>
  </tr>
</table>

<h4>Erb Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td>
      <a href="http://www.kuwata-lab.com/erubis/" title="erubis">erubis</a>
      or erb (included in Ruby)
    </td>
  </tr>
  <tr>
    <td>File Extensions</td>
    <td>
<tt>.erb</tt>, <tt>.rhtml</tt> or <tt>.erubis</tt> (Erubis only)</td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>erb :index</tt></td>
  </tr>
</table>

<h4>Builder Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td>
      <a href="https://github.com/jimweirich/builder" title="builder">builder</a>
    </td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.builder</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>builder { |xml| xml.em "hi" }</tt></td>
  </tr>
</table>

<p>It also takes a block for inline templates (see example).</p>

<h4>Nokogiri Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="http://www.nokogiri.org/" title="nokogiri">nokogiri</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.nokogiri</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>nokogiri { |xml| xml.em "hi" }</tt></td>
  </tr>
</table>

<p>It also takes a block for inline templates (see example).</p>

<h4>Sass Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="http://sass-lang.com/" title="sass">sass</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.sass</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>sass :stylesheet, :style =&gt; :expanded</tt></td>
  </tr>
</table>

<h4>SCSS Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="http://sass-lang.com/" title="sass">sass</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.scss</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>scss :stylesheet, :style =&gt; :expanded</tt></td>
  </tr>
</table>

<h4>Less Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="http://lesscss.org/" title="less">less</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.less</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>less :stylesheet</tt></td>
  </tr>
</table>

<h4>Liquid Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="http://liquidmarkup.org/" title="liquid">liquid</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.liquid</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>liquid :index, :locals =&gt; { :key =&gt; 'value' }</tt></td>
  </tr>
</table>

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

<h4>Markdown Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td>
      Anyone of:
        <a href="https://github.com/davidfstr/rdiscount" title="RDiscount">RDiscount</a>,
        <a href="https://github.com/vmg/redcarpet" title="RedCarpet">RedCarpet</a>,
        <a href="http://deveiate.org/projects/BlueCloth" title="BlueCloth">BlueCloth</a>,
        <a href="http://kramdown.gettalong.org/" title="kramdown">kramdown</a>,
        <a href="https://github.com/bhollis/maruku" title="maruku">maruku</a>
    </td>
  </tr>
  <tr>
    <td>File Extensions</td>
    <td>
<tt>.markdown</tt>, <tt>.mkd</tt> and <tt>.md</tt>
</td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>markdown :index, :layout_engine =&gt; :erb</tt></td>
  </tr>
</table>

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

<pre><code class="language-ruby">erb :overview, :locals =&gt; { :text =&gt; markdown(:introduction) }
</code></pre>

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

<pre><code class="language-ruby">%h1 Hello From Haml!
%p= markdown(:greetings)
</code></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 <code>:layout_engine</code> option.</p>

<h4>Textile Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="http://redcloth.org/" title="RedCloth">RedCloth</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.textile</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>textile :index, :layout_engine =&gt; :erb</tt></td>
  </tr>
</table>

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

<pre><code class="language-ruby">erb :overview, :locals =&gt; { :text =&gt; textile(:introduction) }
</code></pre>

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

<pre><code class="language-ruby">%h1 Hello From Haml!
%p= textile(:greetings)
</code></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 <code>:layout_engine</code> option.</p>

<h4>RDoc Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="http://rdoc.sourceforge.net/" title="RDoc">RDoc</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.rdoc</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>rdoc :README, :layout_engine =&gt; :erb</tt></td>
  </tr>
</table>

<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><code class="language-ruby">erb :overview, :locals =&gt; { :text =&gt; rdoc(:introduction) }
</code></pre>

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

<pre><code class="language-ruby">%h1 Hello From Haml!
%p= rdoc(:greetings)
</code></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 <code>:layout_engine</code> option.</p>

<h4>AsciiDoc Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="http://asciidoctor.org/" title="Asciidoctor">Asciidoctor</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td>
<tt>.asciidoc</tt>, <tt>.adoc</tt> and <tt>.ad</tt>
</td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>asciidoc :README, :layout_engine =&gt; :erb</tt></td>
  </tr>
</table>

<p>Since you cannot call Ruby methods directly from an AsciiDoc template, you
almost always want to pass locals to it.</p>

<h4>Radius Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="https://github.com/jlong/radius" title="Radius">Radius</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.radius</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>radius :index, :locals =&gt; { :key =&gt; 'value' }</tt></td>
  </tr>
</table>

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

<h4>Markaby Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="http://markaby.github.io/" title="Markaby">Markaby</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.mab</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>markaby { h1 "Welcome!" }</tt></td>
  </tr>
</table>

<p>It also takes a block for inline templates (see example).</p>

<h4>RABL Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="https://github.com/nesquena/rabl" title="Rabl">Rabl</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.rabl</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>rabl :index</tt></td>
  </tr>
</table>

<h4>Slim Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="http://slim-lang.com/" title="Slim Lang">Slim Lang</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.slim</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>slim :index</tt></td>
  </tr>
</table>

<h4>Creole Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="https://github.com/minad/creole" title="Creole">Creole</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.creole</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>creole :wiki, :layout_engine =&gt; :erb</tt></td>
  </tr>
</table>

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

<pre><code class="language-ruby">erb :overview, :locals =&gt; { :text =&gt; creole(:introduction) }
</code></pre>

<p>Note that you may also call the <code>creole</code> method from within other templates:</p>

<pre><code class="language-ruby">%h1 Hello From Haml!
%p= creole(:greetings)
</code></pre>

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

<h4>MediaWiki Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="https://github.com/nricciar/wikicloth" title="WikiCloth">WikiCloth</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td>
<tt>.mediawiki</tt> and <tt>.mw</tt>
</td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>mediawiki :wiki, :layout_engine =&gt; :erb</tt></td>
  </tr>
</table>

<p>It is not possible to call methods from MediaWiki markup, nor to pass
locals to it. You therefore will usually use it in combination with
another rendering engine:</p>

<pre><code class="language-ruby">erb :overview, :locals =&gt; { :text =&gt; mediawiki(:introduction) }
</code></pre>

<p>Note that you may also call the <code>mediawiki</code> method from within other
templates:</p>

<pre><code class="language-ruby">%h1 Hello From Haml!
%p= mediawiki(:greetings)
</code></pre>

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

<h4>CoffeeScript Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td>
      <a href="https://github.com/josh/ruby-coffee-script" title="Ruby CoffeeScript">
        CoffeeScript
      </a> and a
      <a href="https://github.com/sstephenson/execjs/blob/master/README.md#readme" title="ExecJS">
        way to execute javascript
      </a>
    </td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.coffee</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>coffee :index</tt></td>
  </tr>
</table>

<h4>Stylus Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td>
      <a href="https://github.com/forgecrafted/ruby-stylus" title="Ruby Stylus">
        Stylus
      </a> and a
      <a href="https://github.com/sstephenson/execjs/blob/master/README.md#readme" title="ExecJS">
        way to execute javascript
      </a>
    </td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.styl</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>stylus :index</tt></td>
  </tr>
</table>

<p>Before being able to use Stylus templates, you need to load <code>stylus</code> and
<code>stylus/tilt</code> first:</p>

<pre><code class="language-ruby">require 'sinatra'
require 'stylus'
require 'stylus/tilt'

get '/' do
  stylus :example
end
</code></pre>

<h4>Yajl Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="https://github.com/brianmario/yajl-ruby" title="yajl-ruby">yajl-ruby</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.yajl</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td>
      <tt>
        yajl :index,
             :locals =&gt; { :key =&gt; 'qux' },
             :callback =&gt; 'present',
             :variable =&gt; 'resource'
      </tt>
    </td>
  </tr>
</table>

<p>The template source is evaluated as a Ruby string, and the
resulting json variable is converted using <code>#to_json</code>:</p>

<pre><code class="language-ruby">json = { :foo =&gt; 'bar' }
json[:baz] = key
</code></pre>

<p>The <code>:callback</code> and <code>:variable</code> options can be used to decorate the rendered
object:</p>

<pre><code class="language-javascript">var resource = {"foo":"bar","baz":"qux"};
present(resource);
</code></pre>

<h4>WLang Templates</h4>

<table>
  <tr>
    <td>Dependency</td>
    <td><a href="https://github.com/blambeau/wlang/" title="WLang">WLang</a></td>
  </tr>
  <tr>
    <td>File Extension</td>
    <td><tt>.wlang</tt></td>
  </tr>
  <tr>
    <td>Example</td>
    <td><tt>wlang :index, :locals =&gt; { :key =&gt; 'value' }</tt></td>
  </tr>
</table>

<p>Since calling ruby methods is not idiomatic in WLang, you almost always
want to pass locals to it. Layouts written in WLang and <code>yield</code> are
supported, though.</p>

<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><code class="language-ruby">get '/:id' do
  @foo = Foo.find(params['id'])
  haml '%h1= @foo.name'
end
</code></pre>

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

<pre><code class="language-ruby">get '/:id' do
  foo = Foo.find(params['id'])
  haml '%h1= bar.name', :locals =&gt; { :bar =&gt; foo }
end
</code></pre>

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

<h3>Templates with <code>yield</code> and nested layouts</h3>

<p>A layout is usually just a template that calls <code>yield</code>.
Such a template can be used either through the <code>:template</code> option as
described above, or it can be rendered with a block as follows:</p>

<pre><code class="language-ruby">erb :post, :layout =&gt; false do
  erb :index
end
</code></pre>

<p>This code is mostly equivalent to <code>erb :index, :layout =&gt; :post</code>.</p>

<p>Passing blocks to rendering methods is most useful for creating nested
layouts:</p>

<pre><code class="language-ruby">erb :main_layout, :layout =&gt; false do
  erb :admin_layout do
    erb :user
  end
end
</code></pre>

<p>This can also be done in fewer lines of code with:</p>

<pre><code class="language-ruby">erb :admin_layout, :layout =&gt; :main_layout do
  erb :user
end
</code></pre>

<p>Currently, the following rendering methods accept a block: <code>erb</code>, <code>haml</code>,
<code>liquid</code>, <code>slim </code>, <code>wlang</code>. Also the general <code>render</code> method accepts a block.</p>

<h3>Inline Templates</h3>

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

<pre><code class="language-ruby">require 'sinatra'

get '/' do
  haml :index
end

__END__

@@ layout
%html
  = yield

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

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

<h3>Named Templates</h3>

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

<pre><code class="language-ruby">template :layout do
  "%html\n  =yield\n"
end

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

get '/' do
  haml :index
end
</code></pre>

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

<pre><code class="language-ruby">get '/' do
  haml :index, :layout =&gt; !request.xhr?
end
</code></pre>

<h3>Associating File Extensions</h3>

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

<pre><code class="language-ruby">Tilt.register :tt, Tilt[:textile]
</code></pre>

<h3>Adding Your Own Template Engine</h3>

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

<pre><code class="language-ruby">Tilt.register :myat, MyAwesomeTemplateEngine

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

get '/' do
  myat :index
end
</code></pre>

<p>Renders <code>./views/index.myat</code>. See https://github.com/rtomayko/tilt to
learn more about Tilt.</p>

<h3>Using Custom Logic for Template Lookup</h3>

<p>To implement your own template lookup mechanism you can write your
own <code>#find_template</code> method:</p>

<pre><code class="language-ruby">configure do
  set :views [ './views/a', './views/b' ]
end

def find_template(views, name, engine, &amp;block)
  Array(views).each do |v|
    super(v, name, engine, &amp;block)
  end
end
</code></pre>

<h2>Filters</h2>

<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><code class="language-ruby">before do
  @note = 'Hi!'
  request.path_info = '/foo/bar/baz'
end

get '/foo/*' do
  @note #=&gt; 'Hi!'
  params['splat'] #=&gt; 'bar/baz'
end
</code></pre>

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

<pre><code class="language-ruby">after do
  puts response.status
end
</code></pre>

<p>Note: Unless you use the <code>body</code> 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><code class="language-ruby">before '/protected/*' do
  authenticate!
end

after '/create/:slug' do |slug|
  session[:last_slug] = slug
end
</code></pre>

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

<pre><code class="language-ruby">before :agent =&gt; /Songbird/ do
  # ...
end

after '/blog/*', :host_name =&gt; 'example.com' do
  # ...
end
</code></pre>

<h2>Helpers</h2>

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

<pre><code class="language-ruby">helpers do
  def bar(name)
    "#{name}bar"
  end
end

get '/:name' do
  bar(params['name'])
end
</code></pre>

<p>Alternatively, helper methods can be separately defined in a module:</p>

<pre><code class="language-ruby">module FooUtils
  def foo(name) "#{name}foo" end
end

module BarUtils
  def bar(name) "#{name}bar" end
end

helpers FooUtils, BarUtils
</code></pre>

<p>The effect is the same as including the modules in the application class.</p>

<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><code class="language-ruby">enable :sessions

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

get '/:value' do
  session['value'] = params['value']
end
</code></pre>

<h4>Session Secret Security</h4>

<p>To improve security, the session data in the cookie is signed with a session
secret using <code>HMAC-SHA1</code>. This session secret should optimally be a
cryptographically secure random value of an appropriate length which for
<code>HMAC-SHA1</code> is greater than or equal to 64 bytes (512 bits, 128 hex
characters). You would be advised not to use a secret that is less than 32
bytes of randomness (256 bits, 64 hex characters). It is therefore <strong>very
important</strong> that you don’t just make the secret up, but instead use a secure
random number generator to create it. Humans are extremely bad at generating
random values.</p>

<p>By default, a 32 byte secure random session secret is generated for you by
Sinatra, but it will change with every restart of your application. If you
have multiple instances of your application, and you let Sinatra generate the
key, each instance would then have a different session key which is probably
not what you want.</p>

<p>For better security and usability it’s
<a href="https://12factor.net/config">recommended</a> that you generate a secure random
secret and store it in an environment variable on each host running your
application so that all of your application instances will share the same
secret. You should periodically rotate this session secret to a new value.
Here are some examples of how you might create a 64 byte secret and set it:</p>

<p><strong>Session Secret Generation</strong></p>

<pre><code class="language-text">$ ruby -e "require 'securerandom'; puts SecureRandom.hex(64)"
99ae8af...snip...ec0f262ac
</code></pre>

<p><strong>Session Secret Generation (Bonus Points)</strong></p>

<p>Use the <a href="https://github.com/cryptosphere/sysrandom">sysrandom gem</a> to prefer
use of system RNG facilities to generate random values instead of
userspace <code>OpenSSL</code> which MRI Ruby currently defaults to:</p>

<pre><code class="language-text">$ gem install sysrandom
Building native extensions.  This could take a while...
Successfully installed sysrandom-1.x
1 gem installed

$ ruby -e "require 'sysrandom/securerandom'; puts SecureRandom.hex(64)"
99ae8af...snip...ec0f262ac
</code></pre>

<p><strong>Session Secret Environment Variable</strong></p>

<p>Set a <code>SESSION_SECRET</code> environment variable for Sinatra to the value you
generated. Make this value persistent across reboots of your host. Since the
method for doing this will vary across systems this is for illustrative
purposes only:</p>

<pre><code class="language-bash"># echo "export SESSION_SECRET=99ae8af...snip...ec0f262ac" &gt;&gt; ~/.bashrc
</code></pre>

<p><strong>Session Secret App Config</strong></p>

<p>Setup your app config to fail-safe to a secure random secret
if the <code>SESSION_SECRET</code> environment variable is not available.</p>

<p>For bonus points use the <a href="https://github.com/cryptosphere/sysrandom">sysrandom
gem</a> here as well:</p>

<pre><code class="language-ruby">require 'securerandom'
# -or- require 'sysrandom/securerandom'
set :session_secret, ENV.fetch('SESSION_SECRET') { SecureRandom.hex(64) }
</code></pre>

<h4>Session Config</h4>

<p>If you want to configure it further, you may also store a hash with options
in the <code>sessions</code> setting:</p>

<pre><code class="language-ruby">set :sessions, :domain =&gt; 'foo.com'
</code></pre>

<p>To share your session across other apps on subdomains of foo.com, prefix the
domain with a <em>.</em> like this instead:</p>

<pre><code class="language-ruby">set :sessions, :domain =&gt; '.foo.com'
</code></pre>

<h4>Choosing Your Own Session Middleware</h4>

<p>Note that <code>enable :sessions</code> 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, one of the following methods can be used:</p>

<pre><code class="language-ruby">enable :sessions
set :session_store, Rack::Session::Pool
</code></pre>

<p>Or to set up sessions with a hash of options:</p>

<pre><code class="language-ruby">set :sessions, :expire_after =&gt; 2592000
set :session_store, Rack::Session::Pool
</code></pre>

<p>Another option is to <strong>not</strong> call <code>enable :sessions</code>, but instead pull in
your middleware of choice as you would any other middleware.</p>

<p>It is important to note that when using this method, session based
protection <strong>will not be enabled by default</strong>.</p>

<p>The Rack middleware to do that will also need to be added:</p>

<pre><code class="language-ruby">use Rack::Session::Pool, :expire_after =&gt; 2592000
use Rack::Protection::RemoteToken
use Rack::Protection::SessionHijacking
</code></pre>

<p>See ‘Configuring attack protection’ for more information.</p>

<h3>Halting</h3>

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

<pre><code class="language-ruby">halt
</code></pre>

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

<pre><code class="language-ruby">halt 410
</code></pre>

<p>Or the body:</p>

<pre><code class="language-ruby">halt 'this will be the body'
</code></pre>

<p>Or both:</p>

<pre><code class="language-ruby">halt 401, 'go away!'
</code></pre>

<p>With headers:</p>

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

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

<pre><code class="language-ruby">halt erb(:error)
</code></pre>

<h3>Passing</h3>

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

<pre><code class="language-ruby">get '/guess/:who' do
  pass unless params['who'] == 'Frank'
  'You got me!'
end

get '/guess/*' do
  'You missed!'
end
</code></pre>

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

<h3>Triggering Another Route</h3>

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

<pre><code class="language-ruby">get '/foo' do
  status, headers, body = call env.merge("PATH_INFO" =&gt; '/bar')
  [status, headers, body.map(&amp;:upcase)]
end

get '/bar' do
  "bar"
end
</code></pre>

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

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

<p>Check out the Rack specification if you want to learn more about <code>call</code>.</p>

<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 <code>body</code> helper method. If you do so, you can use that method from
there on to access the body:</p>

<pre><code class="language-ruby">get '/foo' do
  body "bar"
end

after do
  puts body
end
</code></pre>

<p>It is also possible to pass a block to <code>body</code>, 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><code class="language-ruby">get '/foo' do
  status 418
  headers \
    "Allow"   =&gt; "BREW, POST, GET, PROPFIND, WHEN",
    "Refresh" =&gt; "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt"
  body "I'm a tea pot!"
end
</code></pre>

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

<h3>Streaming Responses</h3>

<p>Sometimes you want to start sending out data while still generating parts of
the response body. In extreme examples, you want to keep sending data until
the client closes the connection. You can use the <code>stream</code> helper to avoid
creating your own wrapper:</p>

<pre><code class="language-ruby">get '/' do
  stream do |out|
    out &lt;&lt; "It's gonna be legen -\n"
    sleep 0.5
    out &lt;&lt; " (wait for it) \n"
    sleep 1
    out &lt;&lt; "- dary!\n"
  end
end
</code></pre>

<p>This allows you to implement streaming APIs,
<a href="https://w3c.github.io/eventsource/">Server Sent Events</a>, and can be used as
the basis for <a href="https://en.wikipedia.org/wiki/WebSocket">WebSockets</a>. It can
also be used to increase throughput if some but not all content depends on a
slow resource.</p>

<p>Note that the streaming behavior, especially the number of concurrent
requests, highly depends on the web server used to serve the application.
Some servers might not even support streaming at all. If the server does not
support streaming, the body will be sent all at once after the block passed
to <code>stream</code> finishes executing. Streaming does not work at all with Shotgun.</p>

<p>If the optional parameter is set to <code>keep_open</code>, it will not call <code>close</code> on
the stream object, allowing you to close it at any later point in the
execution flow. This only works on evented servers, like Thin and Rainbows.
Other servers will still close the stream:</p>

<pre><code class="language-ruby"># long polling

set :server, :thin
connections = []

get '/subscribe' do
  # register a client's interest in server events
  stream(:keep_open) do |out|
    connections &lt;&lt; out
    # purge dead connections
    connections.reject!(&amp;:closed?)
  end
end

post '/:message' do
  connections.each do |out|
    # notify client that a new message has arrived
    out &lt;&lt; params['message'] &lt;&lt; "\n"

    # indicate client to connect again
    out.close
  end

  # acknowledge
  "message received"
end
</code></pre>

<p>It’s also possible for the client to close the connection when trying to
write to the socket. Because of this, it’s recommended to check
<code>out.closed?</code> before trying to write.</p>

<h3>Logging</h3>

<p>In the request scope, the <code>logger</code> helper exposes a <code>Logger</code> instance:</p>

<pre><code class="language-ruby">get '/' do
  logger.info "loading data"
  # ...
end
</code></pre>

<p>This logger will automatically take your Rack handler’s logging settings into
account. If logging is disabled, this method will return a dummy object, so
you do not have to worry about it in your routes and filters.</p>

<p>Note that logging is only enabled for <code>Sinatra::Application</code> by default, so
if you inherit from <code>Sinatra::Base</code>, you probably want to enable it yourself:</p>

<pre><code class="language-ruby">class MyApp &lt; Sinatra::Base
  configure :production, :development do
    enable :logging
  end
end
</code></pre>

<p>To avoid any logging middleware to be set up, set the <code>logging</code> setting to
<code>nil</code>. However, keep in mind that <code>logger</code> will in that case return <code>nil</code>. A
common use case is when you want to set your own logger. Sinatra will use
whatever it will find in <code>env['rack.logger']</code>.</p>

<h3>Mime Types</h3>

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

<pre><code class="language-ruby">configure do
  mime_type :foo, 'text/foo'
end
</code></pre>

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

<pre><code class="language-ruby">get '/' do
  content_type :foo
  "foo foo foo"
end
</code></pre>

<h3>Generating URLs</h3>

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

<pre><code class="language-ruby">%a{:href =&gt; url('/foo')} foo
</code></pre>

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

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

<h3>Browser Redirect</h3>

<p>You can trigger a browser redirect with the <code>redirect</code> helper method:</p>

<pre><code class="language-ruby">get '/foo' do
  redirect to('/bar')
end
</code></pre>

<p>Any additional parameters are handled like arguments passed to <code>halt</code>:</p>

<pre><code class="language-ruby">redirect to('/bar'), 303
redirect 'http://www.google.com/', 'wrong place, buddy'
</code></pre>

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

<pre><code class="language-ruby">get '/foo' do
  "&lt;a href='/bar'&gt;do something&lt;/a&gt;"
end

get '/bar' do
  do_something
  redirect back
end
</code></pre>

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

<pre><code class="language-ruby">redirect to('/bar?sum=42')
</code></pre>

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

<pre><code class="language-ruby">enable :sessions

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

get '/bar' do
  session[:secret]
end
</code></pre>

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

<pre><code class="language-ruby">get '/' do
  cache_control :public
  "cache it!"
end
</code></pre>

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

<pre><code class="language-ruby">before do
  cache_control :public, :must_revalidate, :max_age =&gt; 60
end
</code></pre>

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

<pre><code class="language-ruby">before do
  expires 500, :public, :must_revalidate
end
</code></pre>

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

<pre><code class="language-ruby">get "/article/:id" do
  @article = Article.find params['id']
  last_modified @article.updated_at
  etag @article.sha1
  erb :article
end
</code></pre>

<p>It is also possible to use a
<a href="https://en.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation">weak ETag</a>:</p>

<pre><code class="language-ruby">etag @article.sha1, :weak
</code></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
reverse-proxy caching solution, try
<a href="https://github.com/rtomayko/rack-cache">rack-cache</a>:</p>

<pre><code class="language-ruby">require "rack/cache"
require "sinatra"

use Rack::Cache

get '/' do
  cache_control :public, :max_age =&gt; 36000
  sleep 5
  "hello"
end
</code></pre>

<p>Use the <code>:static_cache_control</code> setting (see below) to add
<code>Cache-Control</code> header info to static files.</p>

<p>According to RFC 2616, your application should behave differently if the
If-Match or If-None-Match header is set to <code>*</code>, depending on whether the
resource requested is already in existence. Sinatra assumes resources for
safe (like get) and idempotent (like put) requests are already in existence,
whereas other resources (for instance post requests) are treated as new
resources. You can change this behavior by passing in a <code>:new_resource</code>
option:</p>

<pre><code class="language-ruby">get '/create' do
  etag '', :new_resource =&gt; true
  Article.create
  erb :new_article
end
</code></pre>

<p>If you still want to use a weak ETag, pass in a <code>:kind</code> option:</p>

<pre><code class="language-ruby">etag '', :new_resource =&gt; true, :kind =&gt; :weak
</code></pre>

<h3>Sending Files</h3>

<p>To return the contents of a file as the response, you can use the <code>send_file</code>
helper method:</p>

<pre><code class="language-ruby">get '/' do
  send_file 'foo.png'
end
</code></pre>

<p>It also takes options:</p>

<pre><code class="language-ruby">send_file 'foo.png', :type =&gt; :jpg
</code></pre>

<p>The options are:</p>

<dl>
  <dt>filename</dt>
    <dd>File name to be used in the response,
    defaults to the real file name.</dd>
  <dt>last_modified</dt>
    <dd>Value for Last-Modified header, defaults to the file's mtime.</dd>

  <dt>type</dt>
    <dd>Value for Content-Type header, guessed from the file extension if
    missing.</dd>

  <dt>disposition</dt>
    <dd>
      Value for Content-Disposition header, possible values: <tt>nil</tt>
      (default), <tt>:attachment</tt> and <tt>:inline</tt>
    </dd>

  <dt>length</dt>
    <dd>Value for Content-Length header, defaults to file size.</dd>

  <dt>status</dt>
    <dd>
      Status code to be sent. Useful when sending a static file as an error
      page. 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.
    </dd>
</dl>

<h3>Accessing the Request Object</h3>

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

<pre><code class="language-ruby"># app running on http://example.com/example
get '/foo' do
  t = %w[text/css text/html application/javascript]
  request.accept              # ['text/html', '*/*']
  request.accept? 'text/xml'  # true
  request.preferred_type(t)   # 'text/html'
  request.body                # request body sent by the client (see below)
  request.scheme              # "http"
  request.script_name         # "/example"
  request.path_info           # "/foo"
  request.port                # 80
  request.request_method      # "GET"
  request.query_string        # ""
  request.content_length      # length of request.body
  request.media_type          # media type of request.body
  request.host                # "example.com"
  request.get?                # true (similar methods for other verbs)
  request.form_data?          # false
  request["some_param"]       # value of some_param parameter. [] is a shortcut to the params hash.
  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                 # "http://example.com/example/foo"
  request.path                # "/example/foo"
  request.ip                  # client IP address
  request.secure?             # false (would be true over ssl)
  request.forwarded?          # true (if running behind a reverse proxy)
  request.env                 # raw env hash handed in by Rack
end
</code></pre>

<p>Some options, like <code>script_name</code> or <code>path_info</code>, can also be written:</p>

<pre><code class="language-ruby">before { request.path_info = "/" }

get "/" do
  "all requests end up here"
end
</code></pre>

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

<pre><code class="language-ruby">post "/api" do
  request.body.rewind  # in case someone already read it
  data = JSON.parse request.body.read
  "Hello #{data['name']}!"
end
</code></pre>

<h3>Attachments</h3>

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

<pre><code class="language-ruby">get '/' do
  attachment
  "store it!"
end
</code></pre>

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

<pre><code class="language-ruby">get '/' do
  attachment "info.txt"
  "store it!"
end
</code></pre>

<h3>Dealing with Date and Time</h3>

<p>Sinatra offers a <code>time_for</code> helper method that generates a Time object from
the given value. It is also able to convert <code>DateTime</code>, <code>Date</code> and similar
classes:</p>

<pre><code class="language-ruby">get '/' do
  pass if Time.now &gt; time_for('Dec 23, 2016')
  "still time"
end
</code></pre>

<p>This method is used internally by <code>expires</code>, <code>last_modified</code> and akin. You
can therefore easily extend the behavior of those methods by overriding
<code>time_for</code> in your application:</p>

<pre><code class="language-ruby">helpers do
  def time_for(value)
    case value
    when :yesterday then Time.now - 24*60*60
    when :tomorrow  then Time.now + 24*60*60
    else super
    end
  end
end

get '/' do
  last_modified :yesterday
  expires :tomorrow
  "hello"
end
</code></pre>

<h3>Looking Up Template Files</h3>

<p>The <code>find_template</code> helper is used to find template files for rendering:</p>

<pre><code class="language-ruby">find_template settings.views, 'foo', Tilt[:haml] do |file|
  puts "could be #{file}"
end
</code></pre>

<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><code class="language-ruby">set :views, ['views', 'templates']

helpers do
  def find_template(views, name, engine, &amp;block)
    Array(views).each { |v| super(v, name, engine, &amp;block) }
  end
end
</code></pre>

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

<pre><code class="language-ruby">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)
  end
end
</code></pre>

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

<p>Note that <code>find_template</code> 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 <code>render</code> will use <code>break</code> 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>

<h2>Configuration</h2>

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

<pre><code class="language-ruby">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') }
end
</code></pre>

<p>Run only when the environment (<code>APP_ENV</code> environment variable) is set to
<code>:production</code>:</p>

<pre><code class="language-ruby">configure :production do
  ...
end
</code></pre>

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

<pre><code class="language-ruby">configure :production, :test do
  ...
end
</code></pre>

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

<pre><code class="language-ruby">configure do
  set :foo, 'bar'
end

get '/' do
  settings.foo? # =&gt; true
  settings.foo  # =&gt; 'bar'
  ...
end
</code></pre>

<h3>Configuring attack protection</h3>

<p>Sinatra is using
<a href="https://github.com/sinatra/rack-protection#readme">Rack::Protection</a> to
defend your application against common, opportunistic attacks. You can
easily disable this behavior (which will open up your application to tons
of common vulnerabilities):</p>

<pre><code class="language-ruby">disable :protection
</code></pre>

<p>To skip a single defense layer, set <code>protection</code> to an options hash:</p>

<pre><code class="language-ruby">set :protection, :except =&gt; :path_traversal
</code></pre>
<p>You can also hand in an array in order to disable a list of protections:</p>

<pre><code class="language-ruby">set :protection, :except =&gt; [:path_traversal, :session_hijacking]
</code></pre>

<p>By default, Sinatra will only set up session based protection if <code>:sessions</code>
have been enabled. See ‘Using Sessions’. Sometimes you may want to set up
sessions “outside” of the Sinatra app, such as in the config.ru or with a
separate <code>Rack::Builder</code> instance. In that case you can still set up session
based protection by passing the <code>:session</code> option:</p>

<pre><code class="language-ruby">set :protection, :session =&gt; true
</code></pre>

<h3>Available Settings</h3>

<dl>
  <dt>absolute_redirects</dt>
    <dd>
      If disabled, Sinatra will allow relative redirects, however, Sinatra
      will no longer conform with RFC 2616 (HTTP 1.1), which only allows
      absolute redirects.
    </dd>
    <dd>
      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 the second
      parameter.
    </dd>
    <dd>Disabled by default.</dd>

  <dt>add_charset</dt>
    <dd>
      Mime types the <tt>content_type</tt> helper will automatically add the
      charset info to. You should add to it rather than overriding this
      option: <tt>settings.add_charset &lt;&lt; "application/foobar"</tt>
    </dd>

  <dt>app_file</dt>
    <dd>
      Path to the main application file, used to detect project root, views
      and public folder and inline templates.
    </dd>

  <dt>bind</dt>
    <dd>
      IP address to bind to (default: <tt>0.0.0.0</tt> <em>or</em>
      <tt>localhost</tt> if your `environment` is set to development). Only
      used for built-in server.
    </dd>

  <dt>default_encoding</dt>
    <dd>Encoding to assume if unknown (defaults to <tt>"utf-8"</tt>).</dd>

  <dt>dump_errors</dt>
    <dd>Display errors in the log.</dd>

  <dt>environment</dt>
    <dd>
      Current environment. Defaults to <tt>ENV['APP_ENV']</tt>, or
      <tt>"development"</tt> if not available.
    </dd>

  <dt>logging</dt>
    <dd>Use the logger.</dd>

  <dt>lock</dt>
    <dd>
      Places a lock around every request, only running processing on request
      per Ruby process concurrently.
    </dd>
    <dd>Enabled if your app is not thread-safe. Disabled by default.</dd>

  <dt>method_override</dt>
    <dd>
      Use <tt>_method</tt> magic to allow put/delete forms in browsers that
      don't support it.
    </dd>

  <dt>mustermann_opts</dt>
  <dd>
    A default hash of options to pass to Mustermann.new when compiling routing
    paths.
  </dd>

  <dt>port</dt>
    <dd>Port to listen on. Only used for built-in server.</dd>

  <dt>prefixed_redirects</dt>
    <dd>
      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 by default.
    </dd>

  <dt>protection</dt>
    <dd>
      Whether or not to enable web attack protections. See protection section
      above.
    </dd>

  <dt>public_dir</dt>
    <dd>Alias for <tt>public_folder</tt>. See below.</dd>

  <dt>public_folder</dt>
    <dd>
      Path to the folder public files are served from. Only used if static
      file serving is enabled (see <tt>static</tt> setting below). Inferred
      from <tt>app_file</tt> setting if not set.
    </dd>

  <dt>quiet</dt>
    <dd>
      Disables logs generated by Sinatra's start and stop commands.
      <tt>false</tt> by default.
    </dd>

  <dt>reload_templates</dt>
    <dd>
      Whether or not to reload templates between requests. Enabled in
      development mode.
    </dd>

  <dt>root</dt>
    <dd>
      Path to project root folder. Inferred from <tt>app_file</tt> setting
      if not set.
    </dd>

  <dt>raise_errors</dt>
    <dd>
      Raise exceptions (will stop application). Enabled by default when
      <tt>environment</tt> is set to <tt>"test"</tt>, disabled otherwise.
    </dd>

  <dt>run</dt>
    <dd>
      If enabled, Sinatra will handle starting the web server. Do not
      enable if using rackup or other means.
    </dd>

  <dt>running</dt>
    <dd>Is the built-in server running now? Do not change this setting!</dd>

  <dt>server</dt>
    <dd>
      Server or list of servers to use for built-in server. Order indicates
      priority, default depends on Ruby implementation.
    </dd>

  <dt>sessions</dt>
    <dd>
      Enable cookie-based sessions support using
      <tt>Rack::Session::Cookie</tt>. See 'Using Sessions' section for more
      information.
    </dd>

  <dt>session_store</dt>
    <dd>
      The Rack session middleware used. Defaults to
      <tt>Rack::Session::Cookie</tt>. See 'Using Sessions' section for more
      information.
    </dd>

  <dt>show_exceptions</dt>
    <dd>
      Show a stack trace in the browser when an exception happens. Enabled by
      default when <tt>environment</tt> is set to <tt>"development"</tt>,
      disabled otherwise.
    </dd>
    <dd>
      Can also be set to <tt>:after_handler</tt> to trigger app-specified
      error handling before showing a stack trace in the browser.
    </dd>

  <dt>static</dt>
    <dd>Whether Sinatra should handle serving static files.</dd>
    <dd>Disable when using a server able to do this on its own.</dd>
    <dd>Disabling will boost performance.</dd>
    <dd>
      Enabled by default in classic style, disabled for modular apps.
    </dd>

  <dt>static_cache_control</dt>
    <dd>
      When Sinatra is serving static files, set this to add
      <tt>Cache-Control</tt> headers to the responses. Uses the
      <tt>cache_control</tt> helper. Disabled by default.
    </dd>
    <dd>
      Use an explicit array when setting multiple values:
      <tt>set :static_cache_control, [:public, :max_age =&gt; 300]</tt>
    </dd>

  <dt>threaded</dt>
    <dd>
      If set to <tt>true</tt>, will tell Thin to use
      <tt>EventMachine.defer</tt> for processing the request.
    </dd>

  <dt>traps</dt>
    <dd>Whether Sinatra should handle system signals.</dd>

  <dt>views</dt>
    <dd>
      Path to the views folder. Inferred from <tt>app_file</tt> setting if
      not set.
    </dd>

  <dt>x_cascade</dt>
    <dd>
      Whether or not to set the X-Cascade header if no route matches.
      Defaults to <tt>true</tt>.
    </dd>
</dl>

<h2>Environments</h2>

<p>There are three predefined <code>environments</code>: <code>"development"</code>,
<code>"production"</code> and <code>"test"</code>. Environments can be set through the
<code>APP_ENV</code> environment variable. The default value is <code>"development"</code>.
In the <code>"development"</code> environment all templates are reloaded between
requests, and special <code>not_found</code> and <code>error</code> handlers display stack
traces in your browser. In the <code>"production"</code> and <code>"test"</code> environments,
templates are cached by default.</p>

<p>To run different environments, set the <code>APP_ENV</code> environment variable:</p>

<pre><code class="language-shell">APP_ENV=production ruby my_app.rb
</code></pre>

<p>You can use predefined methods: <code>development?</code>, <code>test?</code> and <code>production?</code> to
check the current environment setting:</p>

<pre><code class="language-ruby">get '/' do
  if settings.development?
    "development!"
  else
    "not development!"
  end
end
</code></pre>

<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 <code>haml</code>, <code>erb</code>,
<code>halt</code>, etc.</p>

<h3>Not Found</h3>

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

<pre><code class="language-ruby">not_found do
  'This is nowhere to be found.'
end
</code></pre>

<h3>Error</h3>

<p>The <code>error</code> handler is invoked any time an exception is raised from a route
block or a filter. But note in development it will only run if you set the
show exceptions option to <code>:after_handler</code>:</p>

<pre><code class="language-ruby">set :show_exceptions, :after_handler
</code></pre>

<p>The exception object can be obtained from the <code>sinatra.error</code> Rack variable:</p>

<pre><code class="language-ruby">error do
  'Sorry there was a nasty error - ' + env['sinatra.error'].message
end
</code></pre>

<p>Custom errors:</p>

<pre><code class="language-ruby">error MyCustomError do
  'So what happened was...' + env['sinatra.error'].message
end
</code></pre>

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

<pre><code class="language-ruby">get '/' do
  raise MyCustomError, 'something bad'
end
</code></pre>

<p>You get this:</p>

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

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

<pre><code class="language-ruby">error 403 do
  'Access forbidden'
end

get '/secret' do
  403
end
</code></pre>

<p>Or a range:</p>

<pre><code class="language-ruby">error 400..510 do
  'Boom'
end
</code></pre>

<p>Sinatra installs special <code>not_found</code> and <code>error</code> handlers when
running under the development environment to display nice stack traces
and additional debugging information in your browser.</p>

<h2>Rack Middleware</h2>

<p>Sinatra rides on <a href="http://rack.github.io/">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
<code>use</code> method:</p>

<pre><code class="language-ruby">require 'sinatra'
require 'my_custom_middleware'

use Rack::Lint
use MyCustomMiddleware

get '/hello' do
  'Hello World'
end
</code></pre>

<p>The semantics of <code>use</code> are identical to those defined for the
<a href="http://www.rubydoc.info/github/rack/rack/master/Rack/Builder">Rack::Builder</a> DSL
(most frequently used from rackup files). For example, the <code>use</code> method
accepts multiple/variable args as well as blocks:</p>

<pre><code class="language-ruby">use Rack::Auth::Basic do |username, password|
  username == 'admin' &amp;&amp; password == 'secret'
end
</code></pre>

<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 <code>use</code> them explicitly.</p>

<p>You can find useful middleware in
<a href="https://github.com/rack/rack/tree/master/lib/rack">rack</a>,
<a href="https://github.com/rack/rack-contrib#readm">rack-contrib</a>,
or in the <a href="https://github.com/rack/rack/wiki/List-of-Middleware">Rack wiki</a>.</p>

<h2>Testing</h2>

<p>Sinatra tests can be written using any Rack-based testing library or
framework.
<a href="http://www.rubydoc.info/github/brynary/rack-test/master/frames">Rack::Test</a>
is recommended:</p>

<pre><code class="language-ruby">require 'my_sinatra_app'
require 'minitest/autorun'
require 'rack/test'

class MyAppTest &lt; Minitest::Test
  include Rack::Test::Methods

  def app
    Sinatra::Application
  end

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

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

  def test_with_user_agent
    get '/', {}, 'HTTP_USER_AGENT' =&gt; 'Songbird'
    assert_equal "You're using Songbird!", last_response.body
  end
end
</code></pre>

<p>Note: If you are using Sinatra in the modular style, replace
<code>Sinatra::Application</code> above with the class name of your app.</p>

<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 assumes a micro-app style configuration
(e.g., a single application file, <code>./public</code> and <code>./views</code>
directories, logging, exception detail page, etc.). That’s where
<code>Sinatra::Base</code> comes into play:</p>

<pre><code class="language-ruby">require 'sinatra/base'

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

  get '/' do
    'Hello world!'
  end
end
</code></pre>

<p>The methods available to <code>Sinatra::Base</code> subclasses are exactly the same
as those available via the top-level DSL. Most top-level apps can be
converted to <code>Sinatra::Base</code> components with two modifications:</p>

<ul>
  <li>Your file should require <code>sinatra/base</code> instead of <code>sinatra</code>;
otherwise, all of Sinatra’s DSL methods are imported into the main
namespace.</li>
  <li>Put your app’s routes, error handlers, filters, and options in a subclass
of <code>Sinatra::Base</code>.</li>
</ul>

<p><code>Sinatra::Base</code> is a blank slate. Most options are disabled by default,
including the built-in server. See <a href="http://www.sinatrarb.com/configuration.html">Configuring
Settings</a> for details on
available options and their behavior. If you want behavior more similar
to when you define your app at the top level (also known as Classic
style), you can subclass <code>Sinatra::Application</code>:</p>

<pre><code class="language-ruby">require 'sinatra/base'

class MyApp &lt; Sinatra::Application
  get '/' do
    'Hello world!'
  end
end
</code></pre>

<h3>Modular vs. Classic Style</h3>

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

<p>The main disadvantage of using the classic style rather than the modular
style is that you will only have one Sinatra application per Ruby
process. If you plan to use more than one, switch to the modular style.
There is no reason you cannot mix the modular and the classic styles.</p>

<p>If switching from one style to the other, you should be aware of
slightly different default settings:</p>

<table>
  <tr>
    <th>Setting</th>
    <th>Classic</th>
    <th>Modular</th>
    <th>Modular</th>
  </tr>

  <tr>
    <td>app_file</td>
    <td>file loading sinatra</td>
    <td>file subclassing Sinatra::Base</td>
    <td>file subclassing Sinatra::Application</td>
  </tr>

  <tr>
    <td>run</td>
    <td>$0 == app_file</td>
    <td>false</td>
    <td>false</td>
  </tr>

  <tr>
    <td>logging</td>
    <td>true</td>
    <td>false</td>
    <td>true</td>
  </tr>

  <tr>
    <td>method_override</td>
    <td>true</td>
    <td>false</td>
    <td>true</td>
  </tr>

  <tr>
    <td>inline_templates</td>
    <td>true</td>
    <td>false</td>
    <td>true</td>
  </tr>

  <tr>
    <td>static</td>
    <td>true</td>
    <td>File.exist?(public_folder)</td>
    <td>true</td>
  </tr>
</table>

<h3>Serving a Modular Application</h3>

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

<pre><code class="language-ruby"># 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
end
</code></pre>

<p>Start with:</p>

<pre><code class="language-shell">ruby my_app.rb
</code></pre>

<p>Or with a <code>config.ru</code> file, which allows using any Rack handler:</p>

<pre><code class="language-ruby"># config.ru (run with rackup)
require './my_app'
run MyApp
</code></pre>

<p>Run:</p>

<pre><code class="language-shell">rackup -p 4567
</code></pre>

<h3>Using a Classic Style Application with a config.ru</h3>

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

<pre><code class="language-ruby"># app.rb
require 'sinatra'

get '/' do
  'Hello world!'
end
</code></pre>

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

<pre><code class="language-ruby">require './app'
run Sinatra::Application
</code></pre>

<h3>When to use a config.ru?</h3>

<p>A <code>config.ru</code> file is recommended if:</p>

<ul>
  <li>You want to deploy with a different Rack handler (Passenger, Unicorn,
Heroku, …).</li>
  <li>You want to use more than one subclass of <code>Sinatra::Base</code>.</li>
  <li>You want to use Sinatra only for middleware, and not as an endpoint.</li>
</ul>

<p><strong>There is no need to switch to a <code>config.ru</code> simply because you
switched to the modular style, and you don’t have to use the modular
style for running with a <code>config.ru</code>.</strong></p>

<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/Hanami/Roda/…):</p>

<pre><code class="language-ruby">require 'sinatra/base'

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

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

  post('/login') do
    if params['name'] == 'admin' &amp;&amp; params['password'] == 'admin'
      session['user_name'] = params['name']
    else
      redirect '/login'
    end
  end
end

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

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

  get('/') { "Hello #{session['user_name']}." }
end
</code></pre>

<h3>Dynamic Application Creation</h3>

<p>Sometimes you want to create new applications at runtime without having to
assign them to a constant. You can do this with <code>Sinatra.new</code>:</p>

<pre><code class="language-ruby">require 'sinatra/base'
my_app = Sinatra.new { get('/') { "hi" } }
my_app.run!
</code></pre>

<p>It takes the application to inherit from as an optional argument:</p>

<pre><code class="language-ruby"># config.ru (run with rackup)
require 'sinatra/base'

controller = Sinatra.new do
  enable :logging
  helpers MyHelpers
end

map('/a') do
  run Sinatra.new(controller) { get('/') { 'a' } }
end

map('/b') do
  run Sinatra.new(controller) { get('/') { 'b' } }
end
</code></pre>

<p>This is especially useful for testing Sinatra extensions or using Sinatra in
your own library.</p>

<p>This also makes using Sinatra as middleware extremely easy:</p>

<pre><code class="language-ruby">require 'sinatra/base'

use Sinatra do
  get('/') { ... }
end

run RailsProject::Application
</code></pre>

<h2>Scopes and Binding</h2>

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

<h3>Application/Class Scope</h3>

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

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

<pre><code class="language-ruby">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!
  end
end
</code></pre>

<p>You have the application scope binding inside:</p>

<ul>
  <li>Your application class body</li>
  <li>Methods defined by extensions</li>
  <li>The block passed to <code>helpers</code>
</li>
  <li>Procs/blocks used as value for <code>set</code>
</li>
  <li>The block passed to <code>Sinatra.new</code>
</li>
</ul>

<p>You can reach the scope object (the class) like this:</p>

<ul>
  <li>Via the object passed to configure blocks (<code>configure { |c| ... }</code>)</li>
  <li>
<code>settings</code> from within the request scope</li>
</ul>

<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 <code>request</code> and <code>session</code> objects or call rendering methods like
<code>erb</code> or <code>haml</code>. You can access the application scope from within the request
scope via the <code>settings</code> helper:</p>

<pre><code class="language-ruby">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("/#{params['name']}") do
      # Request scope for "/#{params['name']}"
      @value # =&gt; nil (not the same request)
    end

    "Route defined!"
  end
end
</code></pre>

<p>You have the request scope binding inside:</p>

<ul>
  <li>get, head, post, put, delete, options, patch, link and unlink blocks</li>
  <li>before and after filters</li>
  <li>helper methods</li>
  <li>templates/views</li>
</ul>

<h3>Delegation Scope</h3>

<p>The delegation scope just forwards methods to the class scope. However, it
does not behave exactly 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
<code>self</code>). You can explicitly add method delegations by calling
<code>Sinatra::Delegator.delegate :method_name</code>.</p>

<p>You have the delegate scope binding inside:</p>

<ul>
  <li>The top level binding, if you did <code>require "sinatra"</code>
</li>
  <li>An object extended with the <code>Sinatra::Delegator</code> mixin</li>
</ul>

<p>Have a look at the code for yourself: here’s the
<a href="https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/base.rb#L1609-1633">Sinatra::Delegator mixin</a>
being <a href="https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/main.rb#L28-30">extending the main object</a>.</p>

<h2>Command Line</h2>

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

<pre><code class="language-shell">ruby myapp.rb [-h] [-x] [-q] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER]
</code></pre>

<p>Options are:</p>

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

<h3>Multi-threading</h3>

<p><em>Paraphrasing from <a href="http://stackoverflow.com/questions/6278817/is-sinatra-multi-threaded/6282999#6282999)">this StackOverflow answer</a> by Konstantin</em></p>

<p>Sinatra doesn’t impose any concurrency model, but leaves that to the
underlying Rack handler (server) like Thin, Puma or WEBrick. Sinatra
itself is thread-safe, so there won’t be any problem if the Rack handler
uses a threaded model of concurrency. This would mean that when starting
the server, you’d have to specify the correct invocation method for the
specific Rack handler. The following example is a demonstration of how
to start a multi-threaded Thin server:</p>

<pre><code class="language-ruby"># app.rb

require 'sinatra/base'

class App &lt; Sinatra::Base
  get '/' do
    "Hello, World"
  end
end

App.run!

</code></pre>

<p>To start the server, the command would be:</p>

<pre><code class="language-shell">thin --threaded start
</code></pre>

<h2>Requirement</h2>

<p>The following Ruby versions are officially supported:</p>
<dl>
  <dt>Ruby 2.2</dt>
  <dd>
    2.2 is fully supported and recommended. There are currently no plans to
    drop official support for it.
  </dd>

  <dt>Rubinius</dt>
  <dd>
    Rubinius is officially supported (Rubinius &gt;= 2.x). It is recommended to
    <tt>gem install puma</tt>.
  </dd>

  <dt>JRuby</dt>
  <dd>
    The latest stable release of JRuby is officially supported. It is not
    recommended to use C extensions with JRuby. It is recommended to
    <tt>gem install trinidad</tt>.
  </dd>
</dl>

<p>Versions of Ruby prior to 2.2.2 are no longer supported as of Sinatra 2.0.</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>

<ul>
  <li>Older versions of JRuby and Rubinius</li>
  <li>Ruby Enterprise Edition</li>
  <li>MacRuby, Maglev, IronRuby</li>
  <li>Ruby 1.9.0 and 1.9.1 (but we do recommend against using those)</li>
</ul>

<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>We also run our CI against ruby-head (future releases of MRI), but we
can’t guarantee anything, since it is constantly moving. Expect upcoming
2.x releases to be fully supported.</p>

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

<p>If you run MacRuby, you should <code>gem install control_tower</code>.</p>

<p>Sinatra currently doesn’t run on Cardinal, SmallRuby, BlueRuby or any
Ruby version prior to 2.2.</p>

<h2>The Bleeding Edge</h2>

<p>If you would like to use Sinatra’s latest bleeding-edge 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><code class="language-shell">gem install sinatra --pre
</code></pre>

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

<h3>With Bundler</h3>

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

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

<pre><code class="language-shell">gem install bundler
</code></pre>

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

<pre><code class="language-ruby">source 'https://rubygems.org'
gem 'sinatra', :github =&gt; 'sinatra/sinatra'

# other dependencies
gem 'haml'                    # for instance, if you use haml
</code></pre>

<p>Note that you will have to list all your application’s dependencies in
the <code>Gemfile</code>. 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><code class="language-shell">bundle exec ruby myapp.rb
</code></pre>

<h2>Versioning</h2>

<p>Sinatra follows <a href="http://semver.org/">Semantic Versioning</a>, both SemVer and
SemVerTag.</p>

<h2>Further Reading</h2>

<ul>
  <li>
<a href="http://www.sinatrarb.com/">Project Website</a> - Additional documentation,
news, and links to other resources.</li>
  <li>
<a href="http://www.sinatrarb.com/contributing">Contributing</a> - Find a bug? Need
help? Have a patch?</li>
  <li><a href="https://github.com/sinatra/sinatra/issues">Issue tracker</a></li>
  <li><a href="https://twitter.com/sinatra">Twitter</a></li>
  <li><a href="http://groups.google.com/group/sinatrarb/topics">Mailing List</a></li>
  <li>IRC: <a href="irc://chat.freenode.net/#sinatra">#sinatra</a> on http://freenode.net</li>
  <li>
<a href="https://sinatrarb.slack.com">Sinatra &amp; Friends</a> on Slack and see
<a href="https://sinatra-slack.herokuapp.com/">here</a> for an invite.</li>
  <li>
<a href="https://github.com/sinatra/sinatra-book/">Sinatra Book</a> Cookbook Tutorial</li>
  <li>
<a href="http://recipes.sinatrarb.com/">Sinatra Recipes</a> Community
contributed recipes</li>
  <li>API documentation for the <a href="http://www.rubydoc.info/gems/sinatra">latest release</a>
or the <a href="http://www.rubydoc.info/github/sinatra/sinatra">current HEAD</a> on
http://www.rubydoc.info/</li>
  <li><a href="https://travis-ci.org/sinatra/sinatra">CI server</a></li>
</ul>
</body></html>