_includes
Directory actions
More options
Directory actions
More options
_includes
Folders and files
| Name | Name | Last commit date | ||
|---|---|---|---|---|
parent directory.. | ||||
<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 "GET /hello/foo" and "GET /hello/bar"
# params[:name] is 'foo' or 'bar'
"Hello #{params[:name]}!"
end
</pre>
<p>
You can also access named parameters via block parameters:
</p>
<pre>
get '/hello/:name' do |n|
"Hello #{n}!"
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] # => ["hello", "world"]
end
get '/download/*.*' do
# matches /download/path/to/file.xml
params[:splat] # => ["path/to/file", "xml"]
end
</pre>
<p>
Route matching with Regular Expressions:
</p>
<pre>
get %r{/hello/([\w]+)} do
"Hello, #{params[:captures].first}!"
end
</pre>
<p>
Or with a block parameter:
</p>
<pre>
get %r{/hello/([\w]+)} do |c|
"Hello, #{c}!"
end
</pre>
<p>
Routes may include a variety of matching conditions, such as the user
agent:
</p>
<pre>
get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
"You're using Songbird version #{params[:agent][0]}"
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>
<p>
One important thing to remember is that you always have to reference
templates with symbols, even if they’re in a subdirectory (in this
case use <tt>:'subdir/template'</tt>). Rendering methods will render any
strings passed to them directly.
</p>
<h3>Haml Templates</h3>
<p>
The haml gem/library is required to render HAML templates:
</p>
<pre>
## You'll need to require haml in your app
require 'haml'
get '/' do
haml :index
end
</pre>
<p>
Renders <tt>./views/index.haml</tt>.
</p>
<p>
<a href="http://haml.hamptoncatlin.com/docs/rdoc/classes/Haml.html">Haml's
options</a> can be set globally through Sinatra’s configurations, see
<a href="http://www.sinatrarb.com/configuration.html">Options and
Configurations</a>, and overridden on an individual basis.
</p>
<pre>
set :haml, {:format => :html5 } # default Haml format is :xhtml
get '/' do
haml :index, :haml_options => {:format => :html4 } # overridden
end
</pre>
<h3>Erb Templates</h3>
<pre>
## You'll need to require erb in your app
require 'erb'
get '/' do
erb :index
end
</pre>
<p>
Renders <tt>./views/index.erb</tt>
</p>
<h3>Erubis</h3>
<p>
The erubis gem/library is required to render builder templates:
</p>
<pre>
## You'll need to require erubis in your app
require 'erubis'
get '/' do
erubis :index
end
</pre>
<p>
Renders <tt>./views/index.erubis</tt>
</p>
<h3>Builder Templates</h3>
<p>
The builder gem/library is required to render builder templates:
</p>
<pre>
## You'll need to require builder in your app
require 'builder'
get '/' do
content_type 'application/xml', :charset => '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>
## You'll need to require haml or sass in your app
require 'sass'
get '/stylesheet.css' do
content_type 'text/css', :charset => 'utf-8'
sass :stylesheet
end
</pre>
<p>
Renders <tt>./views/stylesheet.sass</tt>.
</p>
<p>
<a href="http://haml.hamptoncatlin.com/docs/rdoc/classes/Sass.html">Sass'
options</a> can be set globally through Sinatra’s configurations, see
<a href="http://www.sinatrarb.com/configuration.html">Options and
Configurations</a>, and overridden on an individual basis.
</p>
<pre>
set :sass, {:style => :compact } # default Sass style is :nested
get '/stylesheet.css' do
content_type 'text/css', :charset => 'utf-8'
sass :stylesheet, :style => :expanded # overridden
end
</pre>
<h3>Less Templates</h3>
<p>
The less gem/library is required to render Less templates:
</p>
<pre>
## You'll need to require less in your app
require 'less'
get '/stylesheet.css' do
content_type 'text/css', :charset => 'utf-8'
less :stylesheet
end
</pre>
<p>
Renders <tt>./views/stylesheet.less</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 => { :foo => foo }
end
</pre>
<p>
This is typically used when rendering templates as partials from within
other templates.
</p>
<h3>Inline 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: 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.
</p>
<h3>Named Templates</h3>
<p>
Templates may also be defined using the top-level <tt>template</tt> method:
</p>
<pre>
template :layout do
"%html\n =yield\n"
end
template :index do
'%div.title Hello World!'
end
get '/' do
haml :index
end
</pre>
<p>
If a template named “layout” exists, it will be used each time
a template is rendered. You can disable layouts by passing <tt>:layout
=> false</tt>.
</p>
<pre>
get '/' do
haml :index, :layout => !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)
"#{name}bar"
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 #=> 'Hi!'
params[:splat] #=> 'bar/baz'
end
</pre>
<p>
After filter are evaluated after each request within the context of the
request and can also modify the request and response. Instance variables
set in before filters and routes are accessible by after filters:
</p>
<pre>
after do
puts response.status
end
</pre>
<h2>Halting</h2>
<p>
To immediately stop a request within a filter or route use:
</p>
<pre>
halt
</pre>
<p>
You can also specify the status when halting …
</p>
<pre>
halt 410
</pre>
<p>
Or the body …
</p>
<pre>
halt 'this will be the body'
</pre>
<p>
Or both …
</p>
<pre>
halt 401, 'go away!'
</pre>
<p>
With headers …
</p>
<pre>
halt 402, {'Content-Type' => 'text/plain'}, 'revenge'
</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'
'You got me!'
end
get '/guess/*' do
'You missed!'
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</h2>
<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 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’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 a filter. The exception object can be obtained from the
<tt>sinatra.error</tt> Rack variable:
</p>
<pre>
error do
'Sorry there was a nasty error - ' + env['sinatra.error'].name
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>
Alternatively, you can install error handler for a status code:
</p>
<pre>
error 403 do
'Access forbidden'
end
get '/secret' do
403
end
</pre>
<p>
Or a range:
</p>
<pre>
error 400..510 do
'Boom'
end
</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’t understand. Use <tt>mime_type</tt> to register them
by file extension:
</p>
<pre>
mime_type :foo, 'text/foo'
</pre>
<p>
You can also use it with the <tt>content_type</tt> helper:
</p>
<pre>
content_type :foo
</pre>
<h2>Rack Middleware</h2>
<p>
Sinatra rides on <a href="http://rack.rubyforge.org/">Rack</a>, a minimal
standard interface for Ruby web frameworks. One of Rack’s most
interesting capabilities for application developers is support for
“middleware” — components that sit between the server and
your application monitoring and/or manipulating the HTTP request/response
to provide various types of common functionality.
</p>
<p>
Sinatra makes building Rack middleware pipelines a cinch via a top-level
<tt>use</tt> method:
</p>
<pre>
require 'sinatra'
require 'my_custom_middleware'
use Rack::Lint
use MyCustomMiddleware
get '/hello' do
'Hello World'
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' && 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’t have to <tt>use</tt> them explicitly.
</p>
<h2>Testing</h2>
<p>
Sinatra tests can be written using any Rack-based testing library or
framework. <a href="http://gitrdoc.com/brynary/rack-test">Rack::Test</a> is
recommended:
</p>
<pre>
require 'my_sinatra_app'
require 'rack/test'
class MyAppTest < Test::Unit::TestCase
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 => 'Frank'
assert_equal 'Hello Frank!', last_response.body
end
def test_with_rack_env
get '/', {}, 'HTTP_USER_AGENT' => 'Songbird'
assert_equal "You're using Songbird!", last_response.body
end
end
</pre>
<p>
NOTE: The built-in Sinatra::Test module and Sinatra::TestHarness class are
deprecated as of the 0.9.2 release.
</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 reuseable components such as Rack
middleware, Rails metal, simple libraries with a server component, or even
Sinatra extensions. The top-level DSL pollutes the Object namespace and
assumes a micro-app style configuration (e.g., a single application file,
./public and ./views directories, logging, exception detail page, etc.).
That’s where Sinatra::Base comes into play:
</p>
<pre>
require 'sinatra/base'
class MyApp < Sinatra::Base
set :sessions, true
set :foo, 'bar'
get '/' do
'Hello world!'
end
end
</pre>
<p>
The MyApp class is an independent Rack component that can act as Rack
middleware, a Rack application, or Rails metal. You can <tt>use</tt> or
<tt>run</tt> this class from a rackup <tt>config.ru</tt> file; or, control
a server component shipped as a library:
</p>
<pre>
MyApp.run! :host => 'localhost', :port => 9090
</pre>
<p>
The methods available to Sinatra::Base subclasses are exactly as those
available via the top-level DSL. Most top-level apps can be converted to
Sinatra::Base components with two modifications:
</p>
<ul>
<li>Your file should require <tt>sinatra/base</tt> instead of <tt>sinatra</tt>;
otherwise, all of Sinatra’s DSL methods are imported into the main
namespace.
</li>
<li>Put your app’s routes, error handlers, filters, and options in a
subclass of Sinatra::Base.
</li>
</ul>
<p>
+Sinatra::Base+ is a blank slate. Most options are disabled by default,
including the built-in server. See <a
href="http://sinatra.github.com/configuration.html">Options and
Configuration</a> for details on available options and their behavior.
</p>
<p>
SIDEBAR: Sinatra’s top-level DSL is implemented using a simple
delegation system. The +Sinatra::Application+ class — a special
subclass of Sinatra::Base — receives all :get, :put, :post, :delete,
:before, :error, :not_found, :configure, and :set messages sent to the
top-level. Have a look at the code for yourself: here’s the <a
href="http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/base.rb#L1128">Sinatra::Delegator
mixin</a> being <a
href="http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/main.rb#L28">included
into the main namespace</a>
</p>
<h2>Command line</h2>
<p>
Sinatra applications can be run directly:
</p>
<pre>
ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER]
</pre>
<p>
Options are:
</p>
<pre>
-h # help
-p # set the port (default is 4567)
-o # set the host (default is 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)
</pre>
<h2>The Bleeding Edge</h2>
<p>
If you would like to use Sinatra’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</tt> directory to the
<tt>LOAD_PATH</tt> in your application:
</p>
<pre>
$LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib'
require 'rubygems'
require 'sinatra'
get '/about' do
"I'm running version " + 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://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="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/topics">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>