Return Values

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

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

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

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

Or, using negative look ahead:

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

Static Files

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

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

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

Views / Templates

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

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

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

Markdown Templates

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

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

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

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

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

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

Textile Templates

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

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

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

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

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

get '/' do
textile :index, :layout_engine => :erb
end

This will render ./views/index.textile with
./views/layout.erb as layout.

RDoc Templates

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

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

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

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

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

get '/' do
rdoc :index, :layout_engine => :erb
end

This will render ./views/index.rdoc with
./views/layout.erb as layout.

Inline Templates

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

Named Templates

Templates may also be defined using the top-level template method:

template :layout do
"%html\n =yield\n"
end
template :index do
'%div.title Hello World!'
end
get '/' do
haml :index
end

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

get '/' do
haml :index, :layout => !request.xhr?
end

Associating File Extensions

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

Filters

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:

before do
@note = 'Hi!'
request.path_info = '/foo/bar/baz'
end
get '/foo/*' do
@note #=> 'Hi!'
params[:splat] #=> 'bar/baz'
end

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

after do
puts response.status
end

Note: Unless you use the body 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.

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

before '/protected/*' do
authenticate!
end
after '/create/:slug' do |slug|
session[:last_slug] = slug
end

Like routes, filters also take conditions:

before :agent => /Songbird/ do
# ...
end
after '/blog/*', :host_name => 'example.com' do
# ...
end

Helpers

Use the top-level helpers method to define helper methods for use
in route handlers and templates:

helpers do
def bar(name)
"#{name}bar"
end
end
get '/:name' do
bar(params[:name])
end

Using Sessions

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

enable :sessions
get '/' do
"value = " << session[:value].inspect
end
get '/:value' do
session[:value] = params[:value]
end

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

use Rack::Session::Pool, :expire_after => 2592000
get '/' do
"value = " << session[:value].inspect
end
get '/:value' do
session[:value] = params[:value]
end

To improve security, the session data in the cookie is signed with a
session secret. A random secret is generate for you by Sinatra. However,
since this secret will change with every start of your application, you
might want to set the secret yourself, so all your application instances
share it:

set :session_secret, 'super secret'

Halting

To immediately stop a request within a filter or route use:

halt

You can also specify the status when halting:

halt 410

Or the body:

halt 'this will be the body'

Or both:

halt 401, 'go away!'

With headers:

halt 402, {'Content-Type' => 'text/plain'}, 'revenge'

It is of course possible to combine a template with halt:

halt erb(:error)

Passing

A route can punt processing to the next matching route using pass:

get '/guess/:who' do
pass unless params[:who] == 'Frank'
'You got me!'
end
get '/guess/*' do
'You missed!'
end

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

Triggering Another Route

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

get '/foo' do
status, headers, body = call env.merge("PATH_INFO" => '/bar')
[status, headers, body.map(&:upcase)]
end
get '/bar' do
"bar"
end

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

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

Check out the Rack specification if you want to learn more about
call.

Setting Body, Status Code and Headers

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

get '/foo' do
body "bar"
end
after do
puts body
end

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

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

before do
expires 500, :public, :must_revalidate
end

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

You can also easily wrap this up in an extension and share with others!

Note that find_template 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 render will use break 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.

main application file, used to detect project root, views and public folder
and inline templates.

bind

IP address to bind to (default: 0.0.0.0). Only used for built-in server.

default_encoding

encoding to assume if unknown (defaults to "utf-8").

dump_errors

display errors in the log.

environment

current environment, defaults to ENV['RACK_ENV'], or
"development" if not available.

logging

use the logger.

lock

Places a lock around every request, only running processing on request per
Ruby process concurrently.

Enabled if your app is not thread-safe. Disabled per default.

method_override

use _method magic to allow put/delete forms in browsers that
don't support it.

port

Port to listen on. Only used for built-in server.

prefixed_redirects

Whether or not to insert request.script_name into redirects if no
absolute path is given. That way redirect '/foo' would
behave like redirect to('/foo'). Disabled per default.

public

folder public files are served from

reload_templates

whether or not to reload templates between requests. Enabled in development
mode and on Ruby 1.8.6 (to compensate a bug in Ruby causing a memory leak).

root

project root folder.

raise_errors

raise exceptions (will stop application).

run

if enabled, Sinatra will handle starting the web server, do not enable if
using rackup or other means.

running

is the built-in server running now? do not change this setting!

server

server or list of servers to use for built-in server. defaults to
['thin', 'mongrel', 'webrick'], order indicates
priority.

sessions

enable cookie based sessions.

show_exceptions

show a stack trace in the browser.

static

Whether Sinatra should handle serving static files. Disable when using a
Server able to do this on its own. Disabling will boost performance.
Enabled per default.

views

views folder.

Error Handling

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

Not Found

When a Sinatra::NotFound exception is raised, or the
response's status code is 404, the not_found handler is
invoked:

not_found do
'This is nowhere to be found.'
end

Error

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

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

Custom errors:

error MyCustomError do
'So what happened was...' + env['sinatra.error'].message
end

Then, if this happens:

get '/' do
raise MyCustomError, 'something bad'
end

You get this:

So what happened was... something bad

Alternatively, you can install an error handler for a status code:

error 403 do
'Access forbidden'
end
get '/secret' do
403
end

Or a range:

error 400..510 do
'Boom'
end

Sinatra installs special not_found and error handlers
when running under the development environment.

Rack Middleware

Sinatra rides on Rack, 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.

Sinatra makes building Rack middleware pipelines a cinch via a top-level
use method:

require 'sinatra'
require 'my_custom_middleware'
use Rack::Lint
use MyCustomMiddleware
get '/hello' do
'Hello World'
end

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

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

Testing

Sinatra tests can be written using any Rack-based testing library or
framework. Rack::Test is
recommended:

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

Sinatra::Base - Middleware, Libraries, and Modular Apps

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

require 'sinatra/base'
class MyApp < Sinatra::Base
set :sessions, true
set :foo, 'bar'
get '/' do
'Hello world!'
end
end

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

Your file should require sinatra/base instead of sinatra;
otherwise, all of Sinatra's DSL methods are imported into the main
namespace.

When to use a config.ru?

You want to deploy with a different Rack handler (Passenger, Unicorn,
Heroku, …).

You want to use more than one subclass of Sinatra::Base.

You want to use Sinatra only for middleware, but not as endpoint.

There is no need to switch to a config.ru only because you
switched to modular style, and you don't have to use modular style for
running with a config.ru.

Using Sinatra as Middleware

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

This is especially useful for testing Sinatra extensions or using Sinatra
in your own library.

This also makes using Sinatra as middleware extremely easy:

require 'sinatra/base'
use Sinatra do
get('/') { ... }
end
run RailsProject::Application

Scopes and Binding

The scope you are currently in determines what methods and variables are
available.

Application/Class Scope

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

Options created via set are methods at class level:

class MyApp < Sinatra::Base
# Hey, I'm in the application scope!
set :foo, 42
foo # => 42
get '/foo' do
# Hey, I'm no longer in the application scope!
end
end

You have the application scope binding inside:

Your application class body

Methods defined by extensions

The block passed to helpers

Procs/blocks used as value for set

The block passed to Sinatra.new

You can reach the scope object (the class) like this:

Via the object passed to configure blocks (configure { |c| ... })

settings from within request scope

Request/Instance Scope

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

Delegation Scope

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

Command Line

-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)
-x # turn on the mutex lock (default is off)

Requirements

It is recommended to install Sinatra on Ruby 1.8.7, 1.9.2, JRuby or
Rubinius.

The following Ruby versions are officially supported:

Ruby 1.8.6

It is not recommended to use 1.8.6 for Sinatra. However, it will be
officially supported until Sinatra 1.3.0 is released. RDoc and CoffeeScript
templates are not supported by this Ruby version. 1.8.6 includes a major
memory leak in its Hash implementation, which is triggered by Sinatra
versions prior to 1.1.1. The current version explicitly prevents this leak
at the cost of performance. You will have to downgrade Rack to 1.1.x, as
Rack >= 1.2 no longer supports 1.8.6.

Ruby 1.8.7

1.8.7 is fully supported, however, if nothing is keeping you from it, we
recommend upgrading to 1.9.2 or switching to JRuby or Rubinius.

Ruby 1.9.2

1.9.2 is supported and recommended. Note that Radius and Markaby are
currently not 1.9 compatible. Do not use 1.9.2p0, it is known to cause
segmentation faults when using Sinatra.

JRuby is officially supported (JRuby >= 1.6.0). No issues with third
party template libraries are known, however, if you choose to use JRuby,
please look into JRuby rack handlers, as the Thin web server is not fully
supported on JRuby. JRuby's support for C extensions is still
experimental, which only affects RDiscount at the moment.

We also keep an eye on upcoming Ruby versions.

The following Ruby implementations are not officially supported but still
are known to run Sinatra:

Older versions of JRuby and Rubinius

MacRuby, Maglev, IronRuby

Ruby 1.9.0 and 1.9.1

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.

We also run our CI against ruby-head (the upcoming 1.9.3), but we can't
guarantee anything, since it is constantly moving. Expect 1.9.3p0 to be
supported.

Sinatra should work on any operating system supported by the chosen Ruby
implementation.

The Bleeding Edge

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

We also push out prerelease gems from time to time, so you can do a

gem install sinatra --pre

To get some of the latest features.

With Bundler

If you want to run your application with the latest Sinatra, using Bundler is the recommended way.