Classy web-development dressed in a DSL (official / canonical repo)
Classy web-development dressed in a DSL (official / canonical repo)
Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort:
# myapp.rb
require 'sinatra'
get '/' do
'Hello world!'
endInstall the gems needed:
gem install sinatra rackup pumaAnd run with:
ruby myapp.rbView 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.
In Sinatra, a route is an HTTP method paired with a URL-matching pattern. Each route is associated with a block:
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 ..
endRoutes 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:
get '/foo' do
# Does not match "GET /foo/"
endRoute patterns may include named parameters, accessible via the
params hash:
get '/hello/:name' do
# matches "GET /hello/foo" and "GET /hello/bar"
# params['name'] is 'foo' or 'bar'
"Hello #{params['name']}!"
endYou can also access named parameters via block parameters:
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}!"
endRoute patterns may also include splat (or wildcard) parameters, accessible
via the params['splat'] array:
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"]
endOr with block parameters:
get '/download/*.*' do |path, ext|
[path, ext] # => ["path/to/file", "xml"]
endRoute matching with Regular Expressions:
get /\/hello\/([\w]+)/ do
"Hello, #{params['captures'].first}!"
endOr with a block parameter:
get %r{/hello/([\w]+)} do |c|
# Matches "GET /meta/hello/world", "GET /hello/world/1234" etc.
"Hello, #{c}!"
endRoute patterns may have optional parameters:
get '/posts/:format?' do
# matches "GET /posts/" and any extension "GET /posts/json", "GET /posts/xml" etc
endRoutes may also utilize query parameters:
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
endBy the way, unless you disable the path traversal attack protection (see below), 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:
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!"
endIt looks like a condition, but it isn't one! These options will
be merged into the global :mustermann_opts hash described
below.
Routes may include a variety of matching conditions, such as the user agent:
get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
"You're using Songbird version #{params['agent'][0]}"
end
get '/foo' do
# Matches non-songbird browsers
endOther available conditions are host_name and provides:
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
endprovides searches the request's Accept header.
You can easily define your own conditions:
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."
endFor a condition that takes multiple values use a splat:
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!"
endThe 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:
[status (Integer), headers (Hash), response body (responds to #each)][status (Integer), response body (responds to #each)]#each and passes nothing but strings to
the given blockThat way we can, for instance, easily implement a streaming example:
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) to reduce
boilerplate and embed the streaming logic in the route.
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:
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
# ...
endNote that the above example might be over-engineered, as it can also be expressed as:
get /.*/ do
pass if request.path_info == "/index"
# ...
endStatic files are served from the ./public directory. You can specify
a different location by setting the :public_folder option:
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 as
http://example.com/css/style.css.
Use the :static_cache_control setting (see below) to add
Cache-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:
set :static_headers, {
'access-control-allow-origin' => '*',
'x-static-asset' => 'served-by-sinatra'
}Each template language is exposed via its own rendering method. These methods simply return a string:
get '/' do
erb :index
endThis renders views/index.erb.
Instead of a template name, you can also just pass in the template content directly:
get '/' do
code = "<%= Time.now %>"
erb code
endTemplates take a second argument, the options hash:
get '/' do
erb :index, :layout => :post
endThis will render views/index.erb embedded in the
views/post.erb (default is views/layout.erb, if it exists).
Any options not understood by Sinatra will be passed on to the template engi
`Sinatra::Extension` and `Sinatra::Namespace` collapse keyword arguments into a positional Hash
`delegate` should move away from `ruby2_keywords`
Should `pass` reset all response state (headers + status), not just content-type?
Silence remaining multi_json 1.21 "MultiJson constant is deprecated" warning (needs ::MultiJSON + gemspec floor bump?)
Support `Sec-Fetch-Site`
`uri`/`url` helper can blow up with `ArgumentError - string contains null byte`
Empty PATH_INFO is (probably) invalid and will (probably) fail in Rack 3.2.
Add the ability to dynamically re-assign the static "folder" (although I realised, I can use symlink as workaround)
Host authorization should be easy to disable
[Documentation / Link] The link to the sinatra book appears to no longer be available