Sinatra Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort: Install the gems needed: And run with: View at: http://localhost:4567 The code you changed will…
Sinatra


Sinatra is a DSL for
quickly creating web applications in Ruby with minimal effort:
ruby
# myapp.rb
require 'sinatra'
get '/' do
'Hello world!'
end
Install the gems needed:
shell
gem install sinatra rackup puma
And run with:
shell
ruby myapp.rb
View at: http://localhost:4567
The code you changed will not take effect until you restart the server.
Please restart the server every time you change or use a code reloader
like rerun or
rack-unreloader.
Table of Contents
- [Sinatra](#sinatra)
yield and nested layouts](#templates-with-yield-and-nested-layouts)
- [Inline Templates](#inline-templates)
- [Named Templates](#named-templates)
- [Associating File Extensions](#associating-file-extensions)
- [Adding Your Own Template Engine](#adding-your-own-template-engine)
- [Using Custom Logic for Template Lookup](#using-custom-logic-for-template-lookup)
- [Filters](#filters)
- [Helpers](#helpers)
- [Using Sessions](#using-sessions)
- [Session Secret Security](#session-secret-security)
- [Session Config](#session-config)
- [Choosing Your Own Session Middleware](#choosing-your-own-session-middleware)
- [Halting](#halting)
- [Passing](#passing)
- [Triggering Another Route](#triggering-another-route)
- [Setting Body, Status Code, and Headers](#setting-body-status-code-and-headers)
- [Streaming Responses](#streaming-responses)
- [Logging](#logging)
- [Mime Types](#mime-types)
- [Generating URLs](#generating-urls)
- [Browser Redirect](#browser-redirect)
- [Cache Control](#cache-control)
- [Sending Files](#sending-files)
- [Accessing the Request Object](#accessing-the-request-object)
- [Attachments](#attachments)
- [Dealing with Date and Time](#dealing-with-date-and-time)
- [Looking Up Template Files](#looking-up-template-files)
- [Configuration](#configuration)
- [Configuring attack protection](#configuring-attack-protection)
- [Available Settings](#available-settings)
- [Lifecycle Events](#lifecycle-events)
- [Environments](#environments)
- [Error Handling](#error-handling)
- [Not Found](#not-found)
- [Error](#error)
- [Rack Middleware](#rack-middleware)
- [Testing](#testing)
- [Sinatra::Base - Middleware, Libraries, and Modular Apps](#sinatrabase---middleware-libraries-and-modular-apps)
- [Modular vs. Classic Style](#modular-vs-classic-style)
- [Serving a Modular Application](#serving-a-modular-application)
- [Using a Classic Style Application with a config.ru](#using-a-classic-style-application-with-a-configru)
- [When to use a config.ru?](#when-to-use-a-configru)
- [Using Sinatra as Middleware](#using-sinatra-as-middleware)
- [Dynamic Application Creation](#dynamic-application-creation)
- [Scopes and Binding](#scopes-and-binding)
- [Application/Class Scope](#applicationclass-scope)
- [Request/Instance Scope](#requestinstance-scope)
- [Delegation Scope](#delegation-scope)
- [Command Line](#command-line)
- [Multi-threading](#multi-threading)
- [Requirement](#requirement)
- [The Bleeding Edge](#the-bleeding-edge)
- [With Bundler](#with-bundler)
- [Versioning](#versioning)
- [Further Reading](#further-reading)
Routes
In Sinatra, a route is an HTTP method paired with a URL-matching pattern.
Each route is associated with a block:
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
Routes are matched in the order they are defined. The first route that
matches the request is invoked.
Routes with trailing slashes are different from the ones without:
ruby
get '/foo' do
# Does not match "GET /foo/"
end
Route patterns may include named parameters, accessible via theparams hash:
ruby
get '/hello/:name' do
# matches "GET /hello/foo" and "GET /hello/bar"
# params['name'] is 'foo' or 'bar'
"Hello #{params['name']}!"
end
You can also access named parameters via block parameters:
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
Route patterns may also include splat (or wildcard) parameters, accessible
via the params['splat'] array:
ruby
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
Or with block parameters:
ruby
get '/download/*.*' do |path, ext|
[path, ext] # => ["path/to/file", "xml"]
end
Route matching with Regular Expressions:
ruby
get /\/hello\/([\w]+)/ do
"Hello, #{params['captures'].first}!"
end
Or with a block parameter:
ruby
get %r{/hello/([\w]+)} do |c|
# Matches "GET /meta/hello/world", "GET /hello/world/1234" etc.
"Hello, #{c}!"
end
Route patterns may have optional parameters:
ruby
get '/posts/:format?' do
# matches "GET /posts/" and any extension "GET /posts/json", "GET /posts/xml" etc
end
Routes may also utilize query parameters:
ruby
get '/posts' do
# matches "GET /posts?title=foo&author=bar"
title = params['title']
author = params['author']
# uses title and author variables; query is optional to the /posts route
end
By the way, unless you disable the path traversal attack protection (see
[below](#configuring-attack-protection)), the request path might be modified before
matching against your routes.
You may customize the Mustermann
options used for a given route by passing in a :mustermann_opts hash:
ruby
get '\A/posts\z', :mustermann_opts => { :type => :regexp, :check_anchors => false } do
# matches /posts exactly, with explicit anchoring
"If you match an anchored pattern clap your hands!"
end
It looks like a [condition](#conditions), but it isn't one! These options will
be merged into the global :mustermann_opts hash described
[below](#available-settings).
Conditions
Routes may include a variety of matching conditions, such as the user agent:
ruby
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
Other available conditions are host_name and provides:
ruby
get '/', :host_name => /^admin\./ do
"Admin Area, Access denied!"
end
get '/', :provides => 'html' do
haml :index
end
get '/', :provides => ['rss', 'atom', 'xml'] do
builder :feed
end
provides searches the request's Accept header.
You can easily define your own conditions:
ruby
set(:probability) { |value| condition { rand <= value } }
get '/win_a_car', :probability => 0.1 do
"You won!"
end
get '/win_a_car' do
"Sorry, you lost."
end
For a condition that takes multiple values use a splat:
ruby
set(:auth) do |*roles| # <- notice the splat here
condition do
unless logged_in? && roles.any? {|role| current_user.in_role? role }
redirect "/login/", 303
end
end
end
get "/my/account/", :auth => [:user, :admin] do
"Your Account Details"
end
get "/only/admin/", :auth => :admin do
"Only admins are allowed here!"
end
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 an object that would either be a valid Rack response, Rack
body object or HTTP status code:
- An Array with three elements:
[status (Integer), headers (Hash), response
- An Array with two elements:
[status (Integer), response body (responds to
- An object that responds to
#eachand passes nothing but strings to
- A Integer representing the status code
ruby
class Stream
def each
100.times { |i| yield "#{i}\n" }
end
end
get('/') { Stream.new }
You can also use the stream helper method ([described below](#streaming-responses)) to reduce
boilerplate and embed the streaming logic in the route.
Custom Route Matchers
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:
ruby
class AllButPattern
def initialize(except)
@except = except
end
def to_pattern(options)
return self
end
def params(route)
return {} unless @except === route
end
end
def all_but(pattern)
AllButPattern.new(pattern)
end
get all_but("/index") do
# ...
end
Note that the above example might be over-engineered, as it can also be
expressed as:
ruby
get /.*/ do
pass if request.path_info == "/index"
# ...
end
Static Files
Static files are served from the ./public directory. You can specify
a different location by setting the :public_folder option:
ruby
set :public_folder, __dir__ + '/static'
Note that the public directory name is not included in the URL. A file./public/css/style.css is made available ashttp://example.com/css/style.css.
Use the :static_cache_control setting (see [below](#cache-control)) to addCache-Control header info.
By default, Sinatra serves static files from the public/ folder without running middleware or filters. To add custom headers (e.g, for CORS or caching), use the :static_headers setting:
ruby
set :static_headers, {
'access-control-allow-origin' => '*',
'x-static-asset' => 'served-by-sinatra'
}
Views / Templates
Each template language is exposed via its own rendering method. These
methods simply return a string:
ruby
get '/' do
erb :index
end
This renders views/index.erb.
Instead of a template name, you can also just pass in the template content
directly:
ruby
get '/' do
code = "<%= Time.now %>"
erb code
end
Templates take a second argument, the options hash:
ruby
get '/' do
erb :index, :layout => :post
end
This will render views/index.erb embedded in theviews/post.erb (default is views/layout.erb, if it exists).
Any options not understood by Sinatra will be passed on to the template
engine:
ruby
get '/' do
haml :index, :format => :html5
end
You can also set options per template language in general:
ruby
set :haml, :format => :html5
get '/' do
haml :index
end
Options passed to the render method override options set via set.
Available Options:
locals
List of locals passed to the document. Handy with partials.
Example: erb "<%= foo %>", :locals => {:foo => "bar"}
default_encoding
String encoding to use if uncertain. Defaults to
settings.default_encoding.
views
Views folder to load templates from. Defaults to settings.views.
layout
Whether to use a layout (true or false). If it's a
Symbol, specifies what template to use. Example:
erb :index, :layout => !request.xhr?
content_type
Content-Type the template produces. Default depends on template language.
scope
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:
ruby
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
ruby
get '/' do
haml '%div.title Hello World'
end
Renders the template string. You can optionally specify :path and:line for a clearer backtrace if there is a filesystem path or line
associated with that string:
ruby
get '/' do
haml '%div.title Hello World', :path => 'examples/file.haml', :line => 3
end
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:
ruby
require 'rdiscount'
get('/') { markdown :index }
Haml Templates
Dependency
haml
File Extension
.haml
Example
haml :index, :format => :html5
Erb Templates
Dependency
erubi
or erb (included in Ruby)
File Extensions
.erb, .rhtml or .erubi (Erubi only)
Example
erb :index
Builder Templates
Dependency
builder
File Extension
.builder
Example
builder { |xml| xml.em "hi"
…
Members
-
sinatra ★ PINNED
Classy web-development dressed in a DSL (official / canonical repo)
Ruby ★ 12k 5d agoExplain → -
mustermann ★ PINNED
your personal string matching expert
Ruby ★ 678 2mo agoExplain → -
rack-protection ▣
NOTE: This project has been merged upstream to sinatra/sinatra
★ 813 8y agoExplain → -
sinatra-book ⑂
Tutorial + Cookbook
Ruby ★ 676 2y agoExplain → -
sinatra-recipes
Community contributed recipes and techniques
CSS ★ 459 2y agoExplain → -
sinatra-contrib ▣
NOTE: This project has been merged upstream to sinatra/sinatra
★ 441 9y agoExplain → -
sinatra.github.com
“The best revenge is massive success.”
HTML ★ 299 26d agoExplain → -
heroku-sinatra-app ⑂ ▣
No description.
Ruby ★ 127 15y agoExplain → -
sinatra-template ⑂ ▣
base template for classic sinatra apps
Ruby ★ 17 10y agoExplain → -
sinatra-prawn ⑂ ▣
Sinatra extension to add support for pdf rendering with Prawn templates.
Ruby ★ 14 17y agoExplain → -
resources
images and things
★ 12 12y agoExplain → -
mustermann-sinatra-extension ⑂ ▣
No description.
★ 1 5y agoExplain →
No repos match these filters.
More creators on gitmyhub
JakeWharton lucidrains rafaballerini hiteshchoudhary IDouble