Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Branch: master

This branch is 1 commit ahead, 547 commits behind sinatra:master

Fetching latest commit…

Cannot retrieve the latest commit at this time

..
Failed to load latest commit information.
CHANGES.txt
README.html
book.html

README.html

<p>
Sinatra is a DSL for quickly creating web-applications in Ruby with minimal
effort:
</p>
<pre>
  # myapp.rb
  require 'rubygems'
  require 'sinatra'
  get '/' do
    'Hello world!'
  end
</pre>
<p>
Install the gem and run with:
</p>
<pre>
  sudo gem install sinatra
  ruby myapp.rb
</pre>
<p>
View at: <a href="http://localhost:4567">localhost:4567</a>
</p>
<h2>Routes</h2>
<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 ..
  end

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

  put '/' do
    .. update something ..
  end

  delete '/' do
    .. annihilate something ..
  end
</pre>
<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 /foo&quot; and &quot;GET /bar&quot;
    # params[:name] is 'foo' or 'bar'
    &quot;Hello #{params[:name]}!&quot;
  end
</pre>
<p>
You can also access named parameters via block parameters:
</p>
<pre>
  get '/hello/:name' do |n|
    &quot;Hello #{n}!&quot;
  end
</pre>
<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;]
  end

  get '/download/*.*' do
    # matches /download/path/to/file.xml
    params[:splat] # =&gt; [&quot;path/to/file&quot;, &quot;xml&quot;]
  end
</pre>
<p>
Route matching with Regular Expressions:
</p>
<pre>
  get %r{/hello/([\w]+)} do
    &quot;Hello, #{params[:captures].first}!&quot;
  end
</pre>
<p>
Or with a block parameter:
</p>
<pre>
  get %r{/hello/([\w]+)} do |c|
    &quot;Hello, #{c}!&quot;
  end
</pre>
<p>
Routes may include a variety of matching conditions, such as the user
agent:
</p>
<pre>
  get '/foo', :agent =&gt; /Songbird (\d\.\d)[\d\/]*?/ do
    &quot;You're using Songbird version #{params[:agent][0]}&quot;
  end

  get '/foo' do
    # Matches non-songbird browsers
  end
</pre>
<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
href="http://example.com/css/style.css">example.com/css/style.css</a></tt>.
</p>
<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>
<h3>Haml Templates</h3>
<p>
The haml gem/library is required to render HAML templates:
</p>
<pre>
  get '/' do
    haml :index
  end
</pre>
<p>
Renders <tt>./views/index.haml</tt>.
</p>
<h3>Erb Templates</h3>
<pre>
  get '/' do
    erb :index
  end
</pre>
<p>
Renders <tt>./views/index.erb</tt>
</p>
<h3>Builder Templates</h3>
<p>
The builder gem/library is required to render builder templates:
</p>
<pre>
  get '/' do
    content_type 'application/xml', :charset =&gt; 'utf-8'
    builder :index
  end
</pre>
<p>
Renders <tt>./views/index.builder</tt>.
</p>
<h3>Sass Templates</h3>
<p>
The sass gem/library is required to render Sass templates:
</p>
<pre>
  get '/stylesheet.css' do
    content_type 'text/css', :charset =&gt; 'utf-8'
    sass :stylesheet
  end
</pre>
<p>
Renders <tt>./views/stylesheet.sass</tt>.
</p>
<h3>Inline Templates</h3>
<pre>
  get '/' do
    haml '%div.title Hello World'
  end
</pre>
<p>
Renders the inlined template string.
</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 direcly accessible by templates:
</p>
<pre>
  get '/:id' do
    @foo = Foo.find(params[:id])
    haml '%h1= @foo.name'
  end
</pre>
<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 }
  end
</pre>
<p>
This is typically used when rendering templates as partials from within
other templates.
</p>
<h3>In-file Templates</h3>
<p>
Templates may be defined at the end of the source file:
</p>
<pre>
  require 'rubygems'
  require 'sinatra'

  get '/' do
    haml :index
  end

  __END__

  @@ layout
  %html
    = yield

  @@ index
  %div.title Hello world!!!!!
</pre>
<p>
NOTE: In-file templates defined in the source file that requires sinatra
are automatically loaded. Call the <tt>use_in_file_templates!</tt> method
explicitly if you have in-file templates in other source files.
</p>
<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;
  end

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

  get '/' do
    haml :index
  end
</pre>
<p>
If a template named &#8220;layout&#8221; exists, it will be used each time
a template is rendered. You can disable layouts by passing <tt>:layout
=&gt; false</tt>.
</p>
<pre>
  get '/' do
    haml :index, :layout =&gt; !request.xhr?
  end
</pre>
<h2>Helpers</h2>
<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)
      &quot;#{name}bar&quot;
    end
  end

  get '/:name' do
    bar(params[:name])
  end
</pre>
<h2>Filters</h2>
<p>
Before filters are evaluated before each request within the context of the
request 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'
  end

  get '/foo/*' do
    @note #=&gt; 'Hi!'
    params[:splat] #=&gt; 'bar/baz'
  end
</pre>
<h2>Halting</h2>
<p>
To immediately stop a request during a before filter or route use:
</p>
<pre>
  halt
</pre>
<p>
You can also specify a body when halting &#8230;
</p>
<pre>
  halt 'this will be the body'
</pre>
<p>
Or set the status and body &#8230;
</p>
<pre>
  halt 401, 'go away!'
</pre>
<h2>Passing</h2>
<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'
    &quot;You got me!&quot;
  end

  get '/guess/*' do
    &quot;You missed!&quot;
  end
</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>
<h2>Configuration and Reloading</h2>
<p>
Sinatra supports multiple environments and reloading. Reloading happens
before each request when running under the <tt>:development</tt>
environment. Wrap your configurations (e.g., database connections,
constants, etc.) in <tt>configure</tt> blocks to protect them from
reloading or to target specific environments.
</p>
<p>
Run once, at startup, in any environment:
</p>
<pre>
  configure do
    ...
  end
</pre>
<p>
Run only when the environment (RACK_ENV environment variable) is set to
<tt>:production</tt>.
</p>
<pre>
  configure :production do
    ...
  end
</pre>
<p>
Run when the environment (RACK_ENV environment variable) is set to either
<tt>:production</tt> or <tt>:test</tt>.
</p>
<pre>
  configure :production, :test do
    ...
  end
</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 <tt>haml</tt>,
<tt>erb</tt>, <tt>halt</tt>, etc.
</p>
<h3>Not Found</h3>
<p>
When a <tt>Sinatra::NotFound</tt> exception is raised, or the
response&#8217;s status code is 404, the <tt>not_found</tt> handler is
invoked:
</p>
<pre>
  not_found do
    'This is nowhere to be found'
  end
</pre>
<h3>Error</h3>
<p>
The <tt>error</tt> handler is invoked any time an exception is raised from
a route block or before 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
  end
</pre>
<p>
Custom errors:
</p>
<pre>
  error MyCustomError do
    'So what happened was...' + request.env['sinatra.error'].message
  end
</pre>
<p>
Then, if this happens:
</p>
<pre>
  get '/' do
    raise MyCustomError, 'something bad'
  end
</pre>
<p>
You get this:
</p>
<pre>
  So what happened was... something bad
</pre>
<p>
Sinatra installs special <tt>not_found</tt> and <tt>error</tt> handlers
when running under the development environment.
</p>
<h2>Mime types</h2>
<p>
When using <tt>send_file</tt> or static files you may have mime types
Sinatra doesn&#8217;t understand. Use <tt>mime</tt> to register them by
file extension:
</p>
<pre>
  mime :foo, 'text/foo'
</pre>
<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&#8217;s most
interesting capabilities for application developers is support for
&#8220;middleware&#8221; &#8212; 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'
  end
</pre>
<p>
The semantics of <tt>use</tt> are identical to those defined for the <a
href="http://rack.rubyforge.org/doc/classes/Rack/Builder.html">Rack::Builder</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'
  end
</pre>
<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&#8217;t have to <tt>use</tt> them explicitly.
</p>
<h2>Testing</h2>
<p>
The Sinatra::Test mixin and Sinatra::TestHarness class include a variety of
helper methods for testing your Sinatra app:
</p>
<pre>
  require 'my_sinatra_app'
  require 'test/unit'
  require 'sinatra/test'

  class MyAppTest &lt; Test::Unit::TestCase
    include Sinatra::Test

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

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

    def test_with_rack_env
      get '/', {}, :agent =&gt; 'Songbird'
      assert_equal &quot;You're using Songbird!&quot;, @response.body
    end
  end
</pre>
<p>
See <a
href="http://www.sinatrarb.com/testing.html">www.sinatrarb.com/testing.html</a>
for more on Sinatra::Test and using it with other test frameworks such as
RSpec, Bacon, and test/spec.
</p>
<h2>Command line</h2>
<p>
Sinatra applications can be run directly:
</p>
<pre>
  ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-s HANDLER]
</pre>
<p>
Options are:
</p>
<pre>
  -h # help
  -p # set the port (default is 4567)
  -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>
<h2>The Bleeding Edge</h2>
<p>
If you would like to use Sinatra&#8217;s latest bleeding code, 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>
Alternatively, you can add the <tt>sinatra/lib&lt;tt&gt; directory to the
&lt;tt&gt;LOAD_PATH</tt> in your application:
</p>
<pre>
  $LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib'
  require 'rubygems'
  require 'sinatra'

  get '/about' do
    &quot;I'm running version &quot; + Sinatra::VERSION
  end
</pre>
<p>
To update the Sinatra sources in the future:
</p>
<pre>
  cd myproject/sinatra
  git pull
</pre>
<h2>More</h2>
<ul>
<li><a href="http://sinatra.github.com/">Project Website</a> - Additional
documentation, news, and links to other resources.

</li>
<li><a href="http://sinatra.github.com/contributing.html">Contributing</a> -
Find a bug? Need help? Have a patch?

</li>
<li><a href="http://sinatra.lighthouseapp.com">Lighthouse</a> - Issue tracking
and release planning.

</li>
<li><a href="http://twitter.com/sinatra">Twitter</a>

</li>
<li><a href="http://groups.google.com/group/sinatrarb">Mailing List</a>

</li>
<li><a href="irc://chat.freenode.net/#sinatra">IRC: #sinatra</a> on <a
href="http://freenode.net">freenode.net</a>

</li>
</ul>
Something went wrong with that request. Please try again.