Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

sinatra

> 编程语言
Open source

Classy web-development dressed in a DSL (official / canonical repo)

12.4K stars0 likes2 views
WebsiteGitHub

About

Classy web-development dressed in a DSL (official / canonical repo)

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:

bash
gem install sinatra rackup puma

And run with:

bash
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
    • Table of Contents
    • Routes
    • Conditions
    • Return Values
    • Custom Route Matchers
    • Static Files
    • Views / Templates
      • Literal Templates
      • Available Template Languages
        • Haml Templates
        • Erb Templates
        • Builder Templates
        • Nokogiri Templates
        • Sass Templates
        • Scss Templates
        • Liquid Templates
        • Markdown Templates
        • RDoc Templates
        • AsciiDoc Templates
        • Markaby Templates
        • RABL Templates
        • Slim Templates
        • Yajl Templates
      • Accessing Variables in Templates
      • Templates with yield and nested layouts
      • Inline Templates
      • Named Templates
      • Associating File Extensions
      • Adding Your Own Template Engine
      • Using Custom Logic for Template Lookup
    • Filters
    • Helpers
      • Using Sessions
        • Session Secret Security
        • Session Config
        • Choosing Your Own Session Middleware
      • Halting
      • Passing
      • Triggering Another Route
      • Setting Body, Status Code, and Headers
      • Streaming Responses
      • Logging
      • Mime Types
      • Generating URLs
      • Browser Redirect
      • Cache Control
      • Sending Files
      • Accessing the Request Object
      • Attachments
      • Dealing with Date and Time
      • Looking Up Template Files
    • Configuration
      • Configuring attack protection
      • Available Settings
    • Lifecycle Events
    • Environments
    • Error Handling
      • Not Found
      • Error
    • Rack Middleware
    • Testing
    • Sinatra::Base - Middleware, Libraries, and Modular Apps
      • Modular vs. Classic Style
      • Serving a Modular Application
      • Using a Classic Style Application with a config.ru
      • When to use a config.ru?
      • Using Sinatra as Middleware
      • Dynamic Application Creation
    • Scopes and Binding
      • Application/Class Scope
      • Request/Instance Scope
      • Delegation Scope
    • Command Line
      • Multi-threading
    • Requirement
    • The Bleeding Edge
      • With Bundler
    • Versioning
    • 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 the params 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), 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, but it isn't one! These options will be merged into the global :mustermann_opts hash described below.

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 body (responds to #each)]
  • An Array with two elements: [status (Integer), response body (responds to #each)]
  • An object that responds to #each and passes nothing but strings to the given block
  • A Integer representing the status code

That way we can, for instance, easily implement a streaming example:

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

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

Issues· 48 open

View all issuesOpen on GitHub
  • #2185

    `Sinatra::Extension` and `Sinatra::Namespace` collapse keyword arguments into a positional Hash

    Updated Jul 27, 2026
  • #2184

    `delegate` should move away from `ruby2_keywords`

    good first issueUpdated Jul 23, 2026
  • #2177

    Should `pass` reset all response state (headers + status), not just content-type?

    Updated Jul 21, 2026
  • #2170

    Silence remaining multi_json 1.21 "MultiJson constant is deprecated" warning (needs ::MultiJSON + gemspec floor bump?)

    Updated Jun 1, 2026
  • #2153

    Support `Sec-Fetch-Site`

    rack-protectionUpdated Apr 14, 2026
  • #2080

    `uri`/`url` helper can blow up with `ArgumentError - string contains null byte`

    bugquestionUpdated Feb 25, 2026
  • #2113

    Empty PATH_INFO is (probably) invalid and will (probably) fail in Rack 3.2.

    bugUpdated Oct 14, 2025
  • #2105

    Add the ability to dynamically re-assign the static "folder" (although I realised, I can use symlink as workaround)

    Updated Oct 12, 2025
  • #2106

    Host authorization should be easy to disable

    featurehelp wantedUpdated Sep 28, 2025
  • #2118

    [Documentation / Link] The link to the sinatra book appears to no longer be available

    Updated Sep 19, 2025

> Tags

Rubyrackrubysinatraweb-framework

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 28, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言