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:

Scope to render template under. Defaults to the application instance. If you
change this, instance variables and helper methods will not be available.

layout_engine

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: set :rdoc, :layout_engine => :erb

layout_options

Special options only used for rendering the layout. Example:
set :rdoc, :layout_options => { :views => 'views/layouts' }

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

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

Literal Templates

get '/'do
haml '%div.title Hello World'end

Renders the template string.

Available Template Languages

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

Markdown Templates

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

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

Slim Templates

Creole Templates

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:

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

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

%h1 HelloFrom Haml!
%p= creole(:greetings)

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

MediaWiki Templates

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:

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

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

%h1 HelloFrom Haml!
%p= mediawiki(:greetings)

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

Named Templates

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:

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:

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

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 as you would any other middleware:

To improve security, the session data in the cookie is signed with a session
secret. A random secret is generated 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'

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

set :sessions, :domain => 'foo.com'

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

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”).

Like body, headers and status with no arguments can be used to access
their current values.

Streaming Responses

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 stream helper to avoid
creating your own wrapper:

This allows you to implement streaming APIs,
Server Sent Events, and can be used as
the basis for WebSockets. It can also be
used to increase throughput if some but not all content depends on a slow
resource.

Note that the streaming behavior, especially the number of concurrent requests,
highly depends on the web server used to serve the application. Some servers,
like WEBRick, 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
stream finishes executing. Streaming does not work at all with Shotgun.

If the optional parameter is set to keep_open, it will not call close 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:

Logging

In the request scope, the logger helper exposes a Logger instance:

get '/'do
logger.info "loading data"# ...end

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.

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

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

Mime Types

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

configure do
mime_type :foo, 'text/foo'end

You can also use it with the content_type helper:

get '/'do
content_type :foo"foo foo foo"end

Generating URLs

For generating URLs you should use the url helper method, for instance, in
Haml:

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_revalidateend

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

According to RFC 2616, your application should behave differently if the If-Match
or If-None-Match header is set to *, 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 :new_resource option:

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.

Accessing the Request Object

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

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.

Configuring attack protection

Sinatra is using
Rack::Protection 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):

disable :protection

To skip a single defense layer, set protection to an options hash:

set :protection, :except => :path_traversal

You can also hand in an array in order to disable a list of protections:

set :protection, :except => [:path_traversal, :session_hijacking]

By default, Sinatra will only set up session based protection if :sessions
has been enabled. Sometimes you want to set up sessions on your own, though. In
that case you can get it to set up session based protections by passing the
:session option:

use Rack::Session::Pool
set :protection, :session => true

Available Settings

absolute_redirects

If disabled, Sinatra will allow relative redirects, however, Sinatra will no
longer conform with RFC 2616 (HTTP 1.1), which only allows absolute redirects.

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

Disabled by default.

add_charset

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

app_file

Path to the 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.0orlocalhost if your `environment` is set to development). 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.

protection

Whether or not to enable web attack protections. See protection section
above.

public_dir

Alias for public_folder. See below.

public_folder

Path to the folder public files are served from. Only used if static
file serving is enabled (see static setting below). Inferred from
app_file setting if not set.

reload_templates

Whether or not to reload templates between requests. Enabled in development
mode.

root

Path to project root folder. Inferred from app_file setting if not
set.

raise_errors

Raise exceptions (will stop application). Enabled by default when
environment is set to "test", disabled otherwise.

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. Order indicates
priority, default depends on Ruby implementation.

sessions

Enable cookie-based sessions support using Rack::Session::Cookie.
See 'Using Sessions' section for more information.

show_exceptions

Show a stack trace in the browser when an exception happens. Enabled by
default when environment is set to "development",
disabled otherwise.

Can also be set to :after_handler to trigger app-specified error
handling before showing 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 in classic style, disabled for modular apps.

static_cache_control

When Sinatra is serving static files, set this to add Cache-Control
headers to the responses. Uses the cache_control helper. Disabled
by default.

If set to true, will tell Thin to use EventMachine.defer
for processing the request.

traps

Whether Sinatra should handle system signals.

views

Path to the views folder. Inferred from app_file setting if
not set.

x_cascade

Whether or not to set the X-Cascade header if no route matches.
Defaults to true.

Environments

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

To run different environments, set the RACK_ENV environment variable:

RACK_ENV=production ruby my_app.rb

You can use predefined methods: development?, test? and production? to
check the current environment setting:

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

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:

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.

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

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

The methods available to Sinatra::Base subclasses are exactly the same 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.

Sinatra::Base is a blank slate. Most options are disabled by default,
including the built-in server. See
Configuring Settings
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 Sinatra::Application.

Modular vs. Classic Style

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.

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.

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

Setting

Classic

Modular

Modular

app_file

file loading sinatra

file subclassing Sinatra::Base

file subclassing Sinatra::Application

run

$0 == app_file

false

false

logging

true

false

true

method_override

true

false

true

inline_templates

true

false

true

static

true

false

true

Serving a Modular Application

There are two common options for starting a modular app, actively starting with
run!:

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, and not as an endpoint.

There is no need to switch to a config.ru simply because you switched to
the modular style, and you don’t have to use the 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/…):

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 or session objects, as there is only a
single application class for all requests.

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

Requirement

The following Ruby versions are officially supported:

Ruby 1.8.7

1.8.7 is fully supported, however, if nothing is keeping you from it, we
recommend upgrading or switching to JRuby or Rubinius. Support for 1.8.7
will not be dropped before Sinatra 2.0. Ruby 1.8.6 is no longer supported.

Ruby 1.9.2

1.9.2 is fully supported. Do not use 1.9.2p0, as it is known to cause
segmentation faults when running Sinatra. Official support will continue
at least until the release of Sinatra 1.5.

Ruby 1.9.3

1.9.3 is fully supported and recommended. Please note that switching to 1.9.3
from an earlier version will invalidate all sessions. 1.9.3 will be supported
until the release of Sinatra 2.0.

Ruby 2.x

2.x is fully supported and recommended. There are currently no plans to drop
official support for it.