[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-7641":3},{"id":4,"name":5,"fullName":6,"owner":5,"repo":5,"description":7,"homepage":8,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":16,"stars7d":17,"stars30d":18,"stars90d":15,"forks30d":15,"starsTrendScore":19,"compositeScore":20,"rankGlobal":9,"rankLanguage":9,"license":21,"archived":22,"fork":22,"defaultBranch":23,"hasWiki":22,"hasPages":22,"topics":24,"createdAt":9,"pushedAt":9,"updatedAt":28,"readmeContent":29,"aiSummary":30,"trendingCount":15,"starSnapshotCount":15,"syncStatus":31,"lastSyncTime":32,"discoverSource":33},7641,"sinatra","sinatra\u002Fsinatra","Classy web-development dressed in a DSL (official \u002F canonical repo)","https:\u002F\u002Fsinatrarb.com",null,"Ruby",12443,2069,360,27,0,1,11,26,5,44.95,"MIT License",false,"main",[25,26,5,27],"rack","ruby","web-framework","2026-06-12 02:01:42","# Sinatra\n\n[![Gem Version](https:\u002F\u002Fbadge.fury.io\u002Frb\u002Fsinatra.svg)](https:\u002F\u002Fbadge.fury.io\u002Frb\u002Fsinatra)\n[![Testing](https:\u002F\u002Fgithub.com\u002Fsinatra\u002Fsinatra\u002Factions\u002Fworkflows\u002Ftest.yml\u002Fbadge.svg)](https:\u002F\u002Fgithub.com\u002Fsinatra\u002Fsinatra\u002Factions\u002Fworkflows\u002Ftest.yml)\n\nSinatra is a [DSL](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FDomain-specific_language) for\nquickly creating web applications in Ruby with minimal effort:\n\n```ruby\n# myapp.rb\nrequire 'sinatra'\n\nget '\u002F' do\n  'Hello world!'\nend\n```\n\nInstall the gems needed:\n\n```shell\ngem install sinatra rackup puma\n```\n\nAnd run with:\n\n```shell\nruby myapp.rb\n```\n\nView at: [http:\u002F\u002Flocalhost:4567](http:\u002F\u002Flocalhost:4567)\n\nThe code you changed will not take effect until you restart the server.\nPlease restart the server every time you change or use a code reloader\nlike [rerun](https:\u002F\u002Fgithub.com\u002Falexch\u002Frerun) or\n[rack-unreloader](https:\u002F\u002Fgithub.com\u002Fjeremyevans\u002Frack-unreloader).\n\n## Table of Contents\n\n- [Sinatra](#sinatra)\n  - [Table of Contents](#table-of-contents)\n  - [Routes](#routes)\n  - [Conditions](#conditions)\n  - [Return Values](#return-values)\n  - [Custom Route Matchers](#custom-route-matchers)\n  - [Static Files](#static-files)\n  - [Views \u002F Templates](#views--templates)\n    - [Literal Templates](#literal-templates)\n    - [Available Template Languages](#available-template-languages)\n      - [Haml Templates](#haml-templates)\n      - [Erb Templates](#erb-templates)\n      - [Builder Templates](#builder-templates)\n      - [Nokogiri Templates](#nokogiri-templates)\n      - [Sass Templates](#sass-templates)\n      - [Scss Templates](#scss-templates)\n      - [Liquid Templates](#liquid-templates)\n      - [Markdown Templates](#markdown-templates)\n      - [RDoc Templates](#rdoc-templates)\n      - [AsciiDoc Templates](#asciidoc-templates)\n      - [Markaby Templates](#markaby-templates)\n      - [RABL Templates](#rabl-templates)\n      - [Slim Templates](#slim-templates)\n      - [Yajl Templates](#yajl-templates)\n    - [Accessing Variables in Templates](#accessing-variables-in-templates)\n    - [Templates with `yield` and nested layouts](#templates-with-yield-and-nested-layouts)\n    - [Inline Templates](#inline-templates)\n    - [Named Templates](#named-templates)\n    - [Associating File Extensions](#associating-file-extensions)\n    - [Adding Your Own Template Engine](#adding-your-own-template-engine)\n    - [Using Custom Logic for Template Lookup](#using-custom-logic-for-template-lookup)\n  - [Filters](#filters)\n  - [Helpers](#helpers)\n    - [Using Sessions](#using-sessions)\n      - [Session Secret Security](#session-secret-security)\n      - [Session Config](#session-config)\n      - [Choosing Your Own Session Middleware](#choosing-your-own-session-middleware)\n    - [Halting](#halting)\n    - [Passing](#passing)\n    - [Triggering Another Route](#triggering-another-route)\n    - [Setting Body, Status Code, and Headers](#setting-body-status-code-and-headers)\n    - [Streaming Responses](#streaming-responses)\n    - [Logging](#logging)\n    - [Mime Types](#mime-types)\n    - [Generating URLs](#generating-urls)\n    - [Browser Redirect](#browser-redirect)\n    - [Cache Control](#cache-control)\n    - [Sending Files](#sending-files)\n    - [Accessing the Request Object](#accessing-the-request-object)\n    - [Attachments](#attachments)\n    - [Dealing with Date and Time](#dealing-with-date-and-time)\n    - [Looking Up Template Files](#looking-up-template-files)\n  - [Configuration](#configuration)\n    - [Configuring attack protection](#configuring-attack-protection)\n    - [Available Settings](#available-settings)\n  - [Lifecycle Events](#lifecycle-events)\n  - [Environments](#environments)\n  - [Error Handling](#error-handling)\n    - [Not Found](#not-found)\n    - [Error](#error)\n  - [Rack Middleware](#rack-middleware)\n  - [Testing](#testing)\n  - [Sinatra::Base - Middleware, Libraries, and Modular Apps](#sinatrabase---middleware-libraries-and-modular-apps)\n    - [Modular vs. Classic Style](#modular-vs-classic-style)\n    - [Serving a Modular Application](#serving-a-modular-application)\n    - [Using a Classic Style Application with a config.ru](#using-a-classic-style-application-with-a-configru)\n    - [When to use a config.ru?](#when-to-use-a-configru)\n    - [Using Sinatra as Middleware](#using-sinatra-as-middleware)\n    - [Dynamic Application Creation](#dynamic-application-creation)\n  - [Scopes and Binding](#scopes-and-binding)\n    - [Application\u002FClass Scope](#applicationclass-scope)\n    - [Request\u002FInstance Scope](#requestinstance-scope)\n    - [Delegation Scope](#delegation-scope)\n  - [Command Line](#command-line)\n    - [Multi-threading](#multi-threading)\n  - [Requirement](#requirement)\n  - [The Bleeding Edge](#the-bleeding-edge)\n    - [With Bundler](#with-bundler)\n  - [Versioning](#versioning)\n  - [Further Reading](#further-reading)\n\n## Routes\n\nIn Sinatra, a route is an HTTP method paired with a URL-matching pattern.\nEach route is associated with a block:\n\n```ruby\nget '\u002F' do\n  .. show something ..\nend\n\npost '\u002F' do\n  .. create something ..\nend\n\nput '\u002F' do\n  .. replace something ..\nend\n\npatch '\u002F' do\n  .. modify something ..\nend\n\ndelete '\u002F' do\n  .. annihilate something ..\nend\n\noptions '\u002F' do\n  .. appease something ..\nend\n\nlink '\u002F' do\n  .. affiliate something ..\nend\n\nunlink '\u002F' do\n  .. separate something ..\nend\n```\n\nRoutes are matched in the order they are defined. The first route that\nmatches the request is invoked.\n\nRoutes with trailing slashes are different from the ones without:\n\n```ruby\nget '\u002Ffoo' do\n  # Does not match \"GET \u002Ffoo\u002F\"\nend\n```\n\nRoute patterns may include named parameters, accessible via the\n`params` hash:\n\n```ruby\nget '\u002Fhello\u002F:name' do\n  # matches \"GET \u002Fhello\u002Ffoo\" and \"GET \u002Fhello\u002Fbar\"\n  # params['name'] is 'foo' or 'bar'\n  \"Hello #{params['name']}!\"\nend\n```\n\nYou can also access named parameters via block parameters:\n\n```ruby\nget '\u002Fhello\u002F:name' do |n|\n  # matches \"GET \u002Fhello\u002Ffoo\" and \"GET \u002Fhello\u002Fbar\"\n  # params['name'] is 'foo' or 'bar'\n  # n stores params['name']\n  \"Hello #{n}!\"\nend\n```\n\nRoute patterns may also include splat (or wildcard) parameters, accessible\nvia the `params['splat']` array:\n\n```ruby\nget '\u002Fsay\u002F*\u002Fto\u002F*' do\n  # matches \u002Fsay\u002Fhello\u002Fto\u002Fworld\n  params['splat'] # => [\"hello\", \"world\"]\nend\n\nget '\u002Fdownload\u002F*.*' do\n  # matches \u002Fdownload\u002Fpath\u002Fto\u002Ffile.xml\n  params['splat'] # => [\"path\u002Fto\u002Ffile\", \"xml\"]\nend\n```\n\nOr with block parameters:\n\n```ruby\nget '\u002Fdownload\u002F*.*' do |path, ext|\n  [path, ext] # => [\"path\u002Fto\u002Ffile\", \"xml\"]\nend\n```\n\nRoute matching with Regular Expressions:\n\n```ruby\nget \u002F\\\u002Fhello\\\u002F([\\w]+)\u002F do\n  \"Hello, #{params['captures'].first}!\"\nend\n```\n\nOr with a block parameter:\n\n```ruby\nget %r{\u002Fhello\u002F([\\w]+)} do |c|\n  # Matches \"GET \u002Fmeta\u002Fhello\u002Fworld\", \"GET \u002Fhello\u002Fworld\u002F1234\" etc.\n  \"Hello, #{c}!\"\nend\n```\n\nRoute patterns may have optional parameters:\n\n```ruby\nget '\u002Fposts\u002F:format?' do\n  # matches \"GET \u002Fposts\u002F\" and any extension \"GET \u002Fposts\u002Fjson\", \"GET \u002Fposts\u002Fxml\" etc\nend\n```\n\nRoutes may also utilize query parameters:\n\n```ruby\nget '\u002Fposts' do\n  # matches \"GET \u002Fposts?title=foo&author=bar\"\n  title = params['title']\n  author = params['author']\n  # uses title and author variables; query is optional to the \u002Fposts route\nend\n```\n\nBy the way, unless you disable the path traversal attack protection (see\n[below](#configuring-attack-protection)), the request path might be modified before\nmatching against your routes.\n\nYou may customize the [Mustermann](https:\u002F\u002Fgithub.com\u002Fsinatra\u002Fmustermann#readme)\noptions used for a given route by passing in a `:mustermann_opts` hash:\n\n```ruby\nget '\\A\u002Fposts\\z', :mustermann_opts => { :type => :regexp, :check_anchors => false } do\n  # matches \u002Fposts exactly, with explicit anchoring\n  \"If you match an anchored pattern clap your hands!\"\nend\n```\n\nIt looks like a [condition](#conditions), but it isn't one! These options will\nbe merged into the global `:mustermann_opts` hash described\n[below](#available-settings).\n\n## Conditions\n\nRoutes may include a variety of matching conditions, such as the user agent:\n\n```ruby\nget '\u002Ffoo', :agent => \u002FSongbird (\\d\\.\\d)[\\d\\\u002F]*?\u002F do\n  \"You're using Songbird version #{params['agent'][0]}\"\nend\n\nget '\u002Ffoo' do\n  # Matches non-songbird browsers\nend\n```\n\nOther available conditions are `host_name` and `provides`:\n\n```ruby\nget '\u002F', :host_name => \u002F^admin\\.\u002F do\n  \"Admin Area, Access denied!\"\nend\n\nget '\u002F', :provides => 'html' do\n  haml :index\nend\n\nget '\u002F', :provides => ['rss', 'atom', 'xml'] do\n  builder :feed\nend\n```\n`provides` searches the request's Accept header.\n\nYou can easily define your own conditions:\n\n```ruby\nset(:probability) { |value| condition { rand \u003C= value } }\n\nget '\u002Fwin_a_car', :probability => 0.1 do\n  \"You won!\"\nend\n\nget '\u002Fwin_a_car' do\n  \"Sorry, you lost.\"\nend\n```\n\nFor a condition that takes multiple values use a splat:\n\n```ruby\nset(:auth) do |*roles|   # \u003C- notice the splat here\n  condition do\n    unless logged_in? && roles.any? {|role| current_user.in_role? role }\n      redirect \"\u002Flogin\u002F\", 303\n    end\n  end\nend\n\nget \"\u002Fmy\u002Faccount\u002F\", :auth => [:user, :admin] do\n  \"Your Account Details\"\nend\n\nget \"\u002Fonly\u002Fadmin\u002F\", :auth => :admin do\n  \"Only admins are allowed here!\"\nend\n```\n\n## Return Values\n\nThe return value of a route block determines at least the response body\npassed on to the HTTP client or at least the next middleware in the\nRack stack. Most commonly, this is a string, as in the above examples.\nBut other values are also accepted.\n\nYou can return an object that would either be a valid Rack response, Rack\nbody object or HTTP status code:\n\n* An Array with three elements: `[status (Integer), headers (Hash), response\n  body (responds to #each)]`\n* An Array with two elements: `[status (Integer), response body (responds to\n  #each)]`\n* An object that responds to `#each` and passes nothing but strings to\n  the given block\n* A Integer representing the status code\n\nThat way we can, for instance, easily implement a streaming example:\n\n```ruby\nclass Stream\n  def each\n    100.times { |i| yield \"#{i}\\n\" }\n  end\nend\n\nget('\u002F') { Stream.new }\n```\n\nYou can also use the `stream` helper method ([described below](#streaming-responses)) to reduce\nboilerplate and embed the streaming logic in the route.\n\n## Custom Route Matchers\n\nAs shown above, Sinatra ships with built-in support for using String\npatterns and regular expressions as route matches. However, it does not\nstop there. You can easily define your own matchers:\n\n```ruby\nclass AllButPattern\n  def initialize(except)\n    @except = except\n  end\n\n  def to_pattern(options)\n    return self\n  end\n\n  def params(route)\n    return {} unless @except === route\n  end\nend\n\ndef all_but(pattern)\n  AllButPattern.new(pattern)\nend\n\nget all_but(\"\u002Findex\") do\n  # ...\nend\n```\n\nNote that the above example might be over-engineered, as it can also be\nexpressed as:\n\n```ruby\nget \u002F.*\u002F do\n  pass if request.path_info == \"\u002Findex\"\n  # ...\nend\n```\n\n## Static Files\n\nStatic files are served from the `.\u002Fpublic` directory. You can specify\na different location by setting the `:public_folder` option:\n\n```ruby\nset :public_folder, __dir__ + '\u002Fstatic'\n```\n\nNote that the public directory name is not included in the URL. A file\n`.\u002Fpublic\u002Fcss\u002Fstyle.css` is made available as\n`http:\u002F\u002Fexample.com\u002Fcss\u002Fstyle.css`.\n\nUse the `:static_cache_control` setting (see [below](#cache-control)) to add\n`Cache-Control` header info.\n\nBy default, Sinatra serves static files from the `public\u002F` folder without running middleware or filters. To add custom headers (e.g, for CORS or caching), use the `:static_headers` setting:\n\n```ruby\n  set :static_headers, {\n    'access-control-allow-origin' => '*',\n    'x-static-asset' => 'served-by-sinatra'\n  }\n```\n\n## Views \u002F Templates\n\nEach template language is exposed via its own rendering method. These\nmethods simply return a string:\n\n```ruby\nget '\u002F' do\n  erb :index\nend\n```\n\nThis renders `views\u002Findex.erb`.\n\nInstead of a template name, you can also just pass in the template content\ndirectly:\n\n```ruby\nget '\u002F' do\n  code = \"\u003C%= Time.now %>\"\n  erb code\nend\n```\n\nTemplates take a second argument, the options hash:\n\n```ruby\nget '\u002F' do\n  erb :index, :layout => :post\nend\n```\n\nThis will render `views\u002Findex.erb` embedded in the\n`views\u002Fpost.erb` (default is `views\u002Flayout.erb`, if it exists).\n\nAny options not understood by Sinatra will be passed on to the template\nengine:\n\n```ruby\nget '\u002F' do\n  haml :index, :format => :html5\nend\n```\n\nYou can also set options per template language in general:\n\n```ruby\nset :haml, :format => :html5\n\nget '\u002F' do\n  haml :index\nend\n```\n\nOptions passed to the render method override options set via `set`.\n\nAvailable Options:\n\n\u003Cdl>\n  \u003Cdt>locals\u003C\u002Fdt>\n  \u003Cdd>\n    List of locals passed to the document. Handy with partials.\n    Example: \u003Ctt>erb \"\u003C%= foo %>\", :locals => {:foo => \"bar\"}\u003C\u002Ftt>\n  \u003C\u002Fdd>\n\n  \u003Cdt>default_encoding\u003C\u002Fdt>\n  \u003Cdd>\n    String encoding to use if uncertain. Defaults to\n    \u003Ctt>settings.default_encoding\u003C\u002Ftt>.\n  \u003C\u002Fdd>\n\n  \u003Cdt>views\u003C\u002Fdt>\n  \u003Cdd>\n    Views folder to load templates from. Defaults to \u003Ctt>settings.views\u003C\u002Ftt>.\n  \u003C\u002Fdd>\n\n  \u003Cdt>layout\u003C\u002Fdt>\n  \u003Cdd>\n    Whether to use a layout (\u003Ctt>true\u003C\u002Ftt> or \u003Ctt>false\u003C\u002Ftt>). If it's a\n    Symbol, specifies what template to use. Example:\n    \u003Ctt>erb :index, :layout => !request.xhr?\u003C\u002Ftt>\n  \u003C\u002Fdd>\n\n  \u003Cdt>content_type\u003C\u002Fdt>\n  \u003Cdd>\n    Content-Type the template produces. Default depends on template language.\n  \u003C\u002Fdd>\n\n  \u003Cdt>scope\u003C\u002Fdt>\n  \u003Cdd>\n    Scope to render template under. Defaults to the application\n    instance. If you change this, instance variables and helper methods\n    will not be available.\n  \u003C\u002Fdd>\n\n  \u003Cdt>layout_engine\u003C\u002Fdt>\n  \u003Cdd>\n    Template engine to use for rendering the layout. Useful for\n    languages that do not support layouts otherwise. Defaults to the\n    engine used for the template. Example: \u003Ctt>set :rdoc, :layout_engine\n    => :erb\u003C\u002Ftt>\n  \u003C\u002Fdd>\n\n  \u003Cdt>layout_options\u003C\u002Fdt>\n  \u003Cdd>\n    Special options only used for rendering the layout. Example:\n    \u003Ctt>set :rdoc, :layout_options => { :views => 'views\u002Flayouts' }\u003C\u002Ftt>\n  \u003C\u002Fdd>\n\u003C\u002Fdl>\n\nTemplates are assumed to be located directly under the `.\u002Fviews`\ndirectory. To use a different views directory:\n\n```ruby\nset :views, settings.root + '\u002Ftemplates'\n```\n\n\nOne important thing to remember is that you always have to reference\ntemplates with symbols, even if they're in a subdirectory (in this case,\nuse: `:'subdir\u002Ftemplate'` or `'subdir\u002Ftemplate'.to_sym`). You must use a\nsymbol because otherwise rendering methods will render any strings\npassed to them directly.\n\n### Literal Templates\n\n```ruby\nget '\u002F' do\n  haml '%div.title Hello World'\nend\n```\n\nRenders the template string. You can optionally specify `:path` and\n`:line` for a clearer backtrace if there is a filesystem path or line\nassociated with that string:\n\n```ruby\nget '\u002F' do\n  haml '%div.title Hello World', :path => 'examples\u002Ffile.haml', :line => 3\nend\n```\n\n### Available Template Languages\n\nSome languages have multiple implementations. To specify what implementation\nto use (and to be thread-safe), you should simply require it first:\n\n```ruby\nrequire 'rdiscount'\nget('\u002F') { markdown :index }\n```\n\n#### Haml Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\u003Ca href=\"http:\u002F\u002Fhaml.info\u002F\" title=\"haml\">haml\u003C\u002Fa>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extension\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.haml\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>haml :index, :format => :html5\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n#### Erb Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\n      \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fjeremyevans\u002Ferubi\" title=\"erubi\">erubi\u003C\u002Fa>\n      or erb (included in Ruby)\n    \u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extensions\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.erb\u003C\u002Ftt>, \u003Ctt>.rhtml\u003C\u002Ftt> or \u003Ctt>.erubi\u003C\u002Ftt> (Erubi only)\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>erb :index\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n#### Builder Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\n      \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fjimweirich\u002Fbuilder\" title=\"builder\">builder\u003C\u002Fa>\n    \u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extension\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.builder\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>builder { |xml| xml.em \"hi\" }\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\nIt also takes a block for inline templates (see [example](#inline-templates)).\n\n#### Nokogiri Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\u003Ca href=\"http:\u002F\u002Fwww.nokogiri.org\u002F\" title=\"nokogiri\">nokogiri\u003C\u002Fa>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extension\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.nokogiri\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>nokogiri { |xml| xml.em \"hi\" }\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\nIt also takes a block for inline templates (see [example](#inline-templates)).\n\n#### Sass Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fntkme\u002Fsass-embedded-host-ruby\" title=\"sass-embedded\">sass-embedded\u003C\u002Fa>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extension\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.sass\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>sass :stylesheet, :style => :expanded\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n#### Scss Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fntkme\u002Fsass-embedded-host-ruby\" title=\"sass-embedded\">sass-embedded\u003C\u002Fa>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extension\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.scss\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>scss :stylesheet, :style => :expanded\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n#### Liquid Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\u003Ca href=\"https:\u002F\u002Fshopify.github.io\u002Fliquid\u002F\" title=\"liquid\">liquid\u003C\u002Fa>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extension\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.liquid\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>liquid :index, :locals => { :key => 'value' }\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\nSince you cannot call Ruby methods (except for `yield`) from a Liquid\ntemplate, you almost always want to pass locals to it.\n\n#### Markdown Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\n      Anyone of:\n        \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fdavidfstr\u002Frdiscount\" title=\"RDiscount\">RDiscount\u003C\u002Fa>,\n        \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fvmg\u002Fredcarpet\" title=\"RedCarpet\">RedCarpet\u003C\u002Fa>,\n        \u003Ca href=\"https:\u002F\u002Fkramdown.gettalong.org\u002F\" title=\"kramdown\">kramdown\u003C\u002Fa>,\n        \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fgjtorikian\u002Fcommonmarker\" title=\"commonmarker\">commonmarker\u003C\u002Fa>\n        \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Falphabetum\u002Fpandoc-ruby\" title=\"pandoc\">pandoc\u003C\u002Fa>\n    \u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extensions\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.markdown\u003C\u002Ftt>, \u003Ctt>.mkd\u003C\u002Ftt> and \u003Ctt>.md\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>markdown :index, :layout_engine => :erb\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\nIt is not possible to call methods from Markdown, nor to pass locals to it.\nYou therefore will usually use it in combination with another rendering\nengine:\n\n```ruby\nerb :overview, :locals => { :text => markdown(:introduction) }\n```\n\nNote that you may also call the `markdown` method from within other\ntemplates:\n\n```ruby\n%h1 Hello From Haml!\n%p= markdown(:greetings)\n```\n\nSince you cannot call Ruby from Markdown, you cannot use layouts written in\nMarkdown. However, it is possible to use another rendering engine for the\ntemplate than for the layout by passing the `:layout_engine` option.\n\n#### RDoc Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\u003Ca href=\"http:\u002F\u002Frdoc.sourceforge.net\u002F\" title=\"RDoc\">RDoc\u003C\u002Fa>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extension\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.rdoc\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>rdoc :README, :layout_engine => :erb\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\nIt is not possible to call methods from RDoc, nor to pass locals to it. You\ntherefore will usually use it in combination with another rendering engine:\n\n```ruby\nerb :overview, :locals => { :text => rdoc(:introduction) }\n```\n\nNote that you may also call the `rdoc` method from within other templates:\n\n```ruby\n%h1 Hello From Haml!\n%p= rdoc(:greetings)\n```\n\nSince you cannot call Ruby from RDoc, you cannot use layouts written in\nRDoc. However, it is possible to use another rendering engine for the\ntemplate than for the layout by passing the `:layout_engine` option.\n\n#### AsciiDoc Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\u003Ca href=\"http:\u002F\u002Fasciidoctor.org\u002F\" title=\"Asciidoctor\">Asciidoctor\u003C\u002Fa>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extension\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.asciidoc\u003C\u002Ftt>, \u003Ctt>.adoc\u003C\u002Ftt> and \u003Ctt>.ad\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>asciidoc :README, :layout_engine => :erb\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\nSince you cannot call Ruby methods directly from an AsciiDoc template, you\nalmost always want to pass locals to it.\n\n#### Markaby Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\u003Ca href=\"https:\u002F\u002Fmarkaby.github.io\u002F\" title=\"Markaby\">Markaby\u003C\u002Fa>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extension\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.mab\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>markaby { h1 \"Welcome!\" }\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\nIt also takes a block for inline templates (see [example](#inline-templates)).\n\n#### RABL Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fnesquena\u002Frabl\" title=\"Rabl\">Rabl\u003C\u002Fa>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extension\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.rabl\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>rabl :index\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n#### Slim Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\u003Ca href=\"https:\u002F\u002Fslim-template.github.io\u002F\" title=\"Slim Lang\">Slim Lang\u003C\u002Fa>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extension\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.slim\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>slim :index\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n#### Yajl Templates\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Ctd>Dependency\u003C\u002Ftd>\n    \u003Ctd>\u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fbrianmario\u002Fyajl-ruby\" title=\"yajl-ruby\">yajl-ruby\u003C\u002Fa>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>File Extension\u003C\u002Ftd>\n    \u003Ctd>\u003Ctt>.yajl\u003C\u002Ftt>\u003C\u002Ftd>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd>Example\u003C\u002Ftd>\n    \u003Ctd>\n      \u003Ctt>\n        yajl :index,\n             :locals => { :key => 'qux' },\n             :callback => 'present',\n             :variable => 'resource'\n      \u003C\u002Ftt>\n    \u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n\nThe template source is evaluated as a Ruby string, and the\nresulting json variable is converted using `#to_json`:\n\n```ruby\njson = { :foo => 'bar' }\njson[:baz] = key\n```\n\nThe `:callback` and `:variable` options can be used to decorate the rendered\nobject:\n\n```javascript\nvar resource = {\"foo\":\"bar\",\"baz\":\"qux\"};\npresent(resource);\n```\n\n### Accessing Variables in Templates\n\nTemplates are evaluated within the same context as route handlers. Instance\nvariables set in route handlers are directly accessible by templates:\n\n```ruby\nget '\u002F:id' do\n  @foo = Foo.find(params['id'])\n  haml '%h1= @foo.name'\nend\n```\n\nOr, specify an explicit Hash of local variables:\n\n```ruby\nget '\u002F:id' do\n  foo = Foo.find(params['id'])\n  haml '%h1= bar.name', :locals => { :bar => foo }\nend\n```\n\nThis is typically used when rendering templates as partials from within\nother templates.\n\n### Templates with `yield` and nested layouts\n\nA layout is usually just a template that calls `yield`.\nSuch a template can be used either through the `:template` option as\ndescribed above, or it can be rendered with a block as follows:\n\n```ruby\nerb :post, :layout => false do\n  erb :index\nend\n```\n\nThis code is mostly equivalent to `erb :index, :layout => :post`.\n\nPassing blocks to rendering methods is most useful for creating nested\nlayouts:\n\n```ruby\nerb :main_layout, :layout => false do\n  erb :admin_layout do\n    erb :user\n  end\nend\n```\n\nThis can also be done in fewer lines of code with:\n\n```ruby\nerb :admin_layout, :layout => :main_layout do\n  erb :user\nend\n```\n\nCurrently, the following rendering methods accept a block: `erb`, `haml`,\n`liquid`, `slim `. Also, the general `render` method accepts a block.\n\n### Inline Templates\n\nTemplates may be defined at the end of the source file:\n\n```ruby\nrequire 'sinatra'\n\nget '\u002F' do\n  haml :index\nend\n\n__END__\n\n@@ layout\n%html\n  != yield\n\n@@ index\n%div.title Hello world.\n```\n\nNOTE: Inline templates defined in the source file that requires Sinatra are\nautomatically loaded. Call `enable :inline_templates` explicitly if you\nhave inline templates in other source files.\n\n### Named Templates\n\nTemplates may also be defined using the top-level `template` method:\n\n```ruby\ntemplate :layout do\n  \"%html\\n  =yield\\n\"\nend\n\ntemplate :index do\n  '%div.title Hello World!'\nend\n\nget '\u002F' do\n  haml :index\nend\n```\n\nIf a template named \"layout\" exists, it will be used each time a template\nis rendered. You can individually disable layouts by passing\n`:layout => false` or disable them by default via\n`set :haml, :layout => false`:\n\n```ruby\nget '\u002F' do\n  haml :index, :layout => !request.xhr?\nend\n```\n\n### Associating File Extensions\n\nTo associate a file extension with a template engine, use\n`Tilt.register`. For instance, if you like to use the file extension\n`tt` for Haml templates, you can do the following:\n\n```ruby\nTilt.register Tilt[:haml], :tt\n```\n\n### Adding Your Own Template Engine\n\nFirst, register your engine with Tilt, then create a rendering method:\n\n```ruby\nTilt.register MyAwesomeTemplateEngine, :myat\n\nhelpers do\n  def myat(*args) render(:myat, *args) end\nend\n\nget '\u002F' do\n  myat :index\nend\n```\n\nRenders `.\u002Fviews\u002Findex.myat`. Learn more about\n[Tilt](https:\u002F\u002Fgithub.com\u002Frtomayko\u002Ftilt#readme).\n\n### Using Custom Logic for Template Lookup\n\nTo implement your own template lookup mechanism you can write your\nown `#find_template` method:\n\n```ruby\nconfigure do\n  set :views, [ '.\u002Fviews\u002Fa', '.\u002Fviews\u002Fb' ]\nend\n\ndef find_template(views, name, engine, &block)\n  Array(views).each do |v|\n    super(v, name, engine, &block)\n  end\nend\n```\n\n## Filters\n\nBefore filters are evaluated before each request within the same context\nas the routes will be and can modify the request and response. Instance\nvariables set in filters are accessible by routes and templates:\n\n```ruby\nbefore do\n  @note = 'Hi!'\n  request.path_info = '\u002Ffoo\u002Fbar\u002Fbaz'\nend\n\nget '\u002Ffoo\u002F*' do\n  @note #=> 'Hi!'\n  params['splat'] #=> 'bar\u002Fbaz'\nend\n```\n\nAfter filters are evaluated after each request within the same context\nas the routes will be and can also modify the request and response.\nInstance variables set in before filters and routes are accessible by\nafter filters:\n\n```ruby\nafter do\n  puts response.status\nend\n```\n\nNote: Unless you use the `body` method rather than just returning a\nString from the routes, the body will not yet be available in the after\nfilter, since it is generated later on.\n\nFilters optionally take a pattern, causing them to be evaluated only if the\nrequest path matches that pattern:\n\n```ruby\nbefore '\u002Fprotected\u002F*' do\n  authenticate!\nend\n\nafter '\u002Fcreate\u002F:slug' do |slug|\n  session[:last_slug] = slug\nend\n```\n\nLike routes, filters also take conditions:\n\n```ruby\nbefore :agent => \u002FSongbird\u002F do\n  # ...\nend\n\nafter '\u002Fblog\u002F*', :host_name => 'example.com' do\n  # ...\nend\n```\n\n## Helpers\n\nUse the top-level `helpers` method to define helper methods for use in\nroute handlers and templates:\n\n```ruby\nhelpers do\n  def bar(name)\n    \"#{name}bar\"\n  end\nend\n\nget '\u002F:name' do\n  bar(params['name'])\nend\n```\n\nAlternatively, helper methods can be separately defined in a module:\n\n```ruby\nmodule FooUtils\n  def foo(name) \"#{name}foo\" end\nend\n\nmodule BarUtils\n  def bar(name) \"#{name}bar\" end\nend\n\nhelpers FooUtils, BarUtils\n```\n\nThe effect is the same as including the modules in the application class.\n\n### Using Sessions\n\nA session is used to keep state during requests. If activated, you have one\nsession hash per user session:\n\n```ruby\nenable :sessions\n\nget '\u002F' do\n  \"value = \" \u003C\u003C session[:value].inspect\nend\n\nget '\u002F:value' do\n  session['value'] = params['value']\nend\n```\n\n#### Session Secret Security\n\nTo improve security, the session data in the cookie is signed with a session\nsecret using `HMAC-SHA1`. This session secret should optimally be a\ncryptographically secure random value of an appropriate length which for\n`HMAC-SHA1` is greater than or equal to 64 bytes (512 bits, 128 hex\ncharacters). You would be advised not to use a secret that is less than 32\nbytes of randomness (256 bits, 64 hex characters). It is therefore **very\nimportant** that you don't just make the secret up, but instead use a secure\nrandom number generator to create it. Humans are extremely bad at generating\nrandom values.\n\nBy default, a 32 byte secure random session secret is generated for you by\nSinatra, but it will change with every restart of your application. If you\nhave multiple instances of your application, and you let Sinatra generate the\nkey, each instance would then have a different session key which is probably\nnot what you want.\n\nFor better security and usability it's\n[recommended](https:\u002F\u002F12factor.net\u002Fconfig) that you generate a secure random\nsecret and store it in an environment variable on each host running your\napplication so that all of your application instances will share the same\nsecret. You should periodically rotate this session secret to a new value.\nHere are some examples of how you might create a 64-byte secret and set it:\n\n**Session Secret Generation**\n\n```text\n$ ruby -e \"require 'securerandom'; puts SecureRandom.hex(64)\"\n99ae8af...snip...ec0f262ac\n```\n\n**Session Secret Environment Variable**\n\nSet a `SESSION_SECRET` environment variable for Sinatra to the value you\ngenerated. Make this value persistent across reboots of your host. Since the\nmethod for doing this will vary across systems this is for illustrative\npurposes only:\n\n```bash\n# echo \"export SESSION_SECRET=99ae8af...snip...ec0f262ac\" >> ~\u002F.bashrc\n```\n\n**Session Secret App Config**\n\nSet up your app config to fail-safe to a secure random secret\nif the `SESSION_SECRET` environment variable is not available:\n\n```ruby\nrequire 'securerandom'\nset :session_secret, ENV.fetch('SESSION_SECRET') { SecureRandom.hex(64) }\n```\n\n#### Session Config\n\nIf you want to configure it further, you may also store a hash with options\nin the `sessions` setting:\n\n```ruby\nset :sessions, :domain => 'foo.com'\n```\n\nTo share your session across other apps on subdomains of foo.com, prefix the\ndomain with a *.* like this instead:\n\n```ruby\nset :sessions, :domain => '.foo.com'\n```\n\n#### Choosing Your Own Session Middleware\n\nNote that `enable :sessions` actually stores all data in a cookie. This\nmight not always be what you want (storing lots of data will increase your\ntraffic, for instance). You can use any Rack session middleware in order to\ndo so, one of the following methods can be used:\n\n```ruby\nenable :sessions\nset :session_store, Rack::Session::Pool\n```\n\nOr to set up sessions with a hash of options:\n\n```ruby\nset :sessions, :expire_after => 2592000\nset :session_store, Rack::Session::Pool\n```\n\nAnother option is to **not** call `enable :sessions`, but instead pull in\nyour middleware of choice as you would any other middleware.\n\nIt is important to note that when using this method, session based\nprotection **will not be enabled by default**.\n\nThe Rack middleware to do that will also need to be added:\n\n```ruby\nuse Rack::Session::Pool, :expire_after => 2592000\nuse Rack::Protection::RemoteToken\nuse Rack::Protection::SessionHijacking\n```\n\nSee '[Configuring attack protection](#configuring-attack-protection)' for more information.\n\n### Halting\n\nTo immediately stop a request within a filter or route use:\n\n```ruby\nhalt\n```\n\nYou can also specify the status when halting:\n\n```ruby\nhalt 410\n```\n\nOr the body:\n\n```ruby\nhalt 'this will be the body'\n```\n\nOr both:\n\n```ruby\nhalt 401, 'go away!'\n```\n\nWith headers:\n\n```ruby\nhalt 402, {'Content-Type' => 'text\u002Fplain'}, 'revenge'\n```\n\nIt is of course possible to combine a template with `halt`:\n\n```ruby\nhalt erb(:error)\n```\n\n### Passing\n\nA route can punt processing to the next matching route using `pass`:\n\n```ruby\nget '\u002Fguess\u002F:who' do\n  pass unless params['who'] == 'Frank'\n  'You got me!'\nend\n\nget '\u002Fguess\u002F*' do\n  'You missed!'\nend\n```\n\nThe route block is immediately exited and control continues with the next\nmatching route. If no matching route is found, a 404 is returned.\n\n### Triggering Another Route\n\nSometimes `pass` is not what you want, instead, you would like to get the\nresult of calling another route. Simply use `call` to achieve this:\n\n```ruby\nget '\u002Ffoo' do\n  status, headers, body = call env.merge(\"PATH_INFO\" => '\u002Fbar')\n  [status, headers, body.map(&:upcase)]\nend\n\nget '\u002Fbar' do\n  \"bar\"\nend\n```\n\nNote that in the example above, you would ease testing and increase\nperformance by simply moving `\"bar\"` into a helper used by both `\u002Ffoo` and\n`\u002Fbar`.\n\nIf you want the request to be sent to the same application instance rather\nthan a duplicate, use `call!` instead of `call`.\n\nCheck out the Rack specification if you want to learn more about `call`.\n\n### Setting Body, Status Code, and Headers\n\nIt is possible and recommended to set the status code and response body with\nthe return value of the route block. However, in some scenarios, you might\nwant to set the body at an arbitrary point in the execution flow. You can do\nso with the `body` helper method. If you do so, you can use that method from\nthereon to access the body:\n\n```ruby\nget '\u002Ffoo' do\n  body \"bar\"\nend\n\nafter do\n  puts body\nend\n```\n\nIt is also possible to pass a block to `body`, which will be executed by the\nRack handler (this can be used to implement streaming, [see \"Return Values\"](#return-values)).\n\nSimilar to the body, you can also set the status code and headers:\n\n```ruby\nget '\u002Ffoo' do\n  status 418\n  headers \\\n    \"Allow\"   => \"BREW, POST, GET, PROPFIND, WHEN\",\n    \"Refresh\" => \"Refresh: 20; https:\u002F\u002Fietf.org\u002Frfc\u002Frfc2324.txt\"\n  body \"I'm a teapot!\"\nend\n```\n\nLike `body`, `headers` and `status` with no arguments can be used to access\ntheir current values.\n\n### Streaming Responses\n\nSometimes you want to start sending out data while still generating parts of\nthe response body. In extreme examples, you want to keep sending data until\nthe client closes the connection. You can use the `stream` helper to avoid\ncreating your own wrapper:\n\n```ruby\nget '\u002F' do\n  stream do |out|\n    out \u003C\u003C \"It's gonna be legen -\\n\"\n    sleep 0.5\n    out \u003C\u003C \" (wait for it) \\n\"\n    sleep 1\n    out \u003C\u003C \"- dary!\\n\"\n  end\nend\n```\n\nThis allows you to implement streaming APIs,\n[Server Sent Events](https:\u002F\u002Fw3c.github.io\u002Feventsource\u002F), and can be used as\nthe basis for [WebSockets](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FWebSocket). It can\nalso be used to increase throughput if some but not all content depends on a\nslow resource.\n\nNote that the streaming behavior, especially the number of concurrent\nrequests, highly depends on the webserver used to serve the application.\nSome servers might not even support streaming at all. If the server does not\nsupport streaming, the body will be sent all at once after the block passed\nto `stream` finishes executing. Streaming does not work at all with Shotgun.\n\nIf the optional parameter is set to `keep_open`, it will not call `close` on\nthe stream object, allowing you to close it at any later point in the\nexecution flow.\n\nYou can have a look at the [chat example](https:\u002F\u002Fgithub.com\u002Fsinatra\u002Fsinatra\u002Fblob\u002Fmain\u002Fexamples\u002Fchat.rb)\n\nIt's also possible for the client to close the connection when trying to\nwrite to the socket. Because of this, it's recommended to check\n`out.closed?` before trying to write.\n\n### Logging\n\nIn the request scope, the `logger` helper exposes a `Logger` instance:\n\n```ruby\nget '\u002F' do\n  logger.info \"loading data\"\n  # ...\nend\n```\n\nThis logger will automatically take your Rack handler's logging settings into\naccount. If logging is disabled, this method will return a dummy object, so\nyou do not have to worry about it in your routes and filters.\n\nNote that logging is only enabled for `Sinatra::Application` by default, so\nif you inherit from `Sinatra::Base`, you probably want to enable it yourself:\n\n```ruby\nclass MyApp \u003C Sinatra::Base\n  configure :production, :development do\n    enable :logging\n  end\nend\n```\n\nTo avoid any logging middleware to be set up, set the `logging` option to\n`nil`. However, keep in mind that `logger` will in that case return `nil`. A\ncommon use case is when you want to set your own logger. Sinatra will use\nwhatever it will find in `env['rack.logger']`.\n\n### Mime Types\n\nWhen using `send_file` or static files you may have mime types Sinatra\ndoesn't understand. Use `mime_type` to register them by file extension:\n\n```ruby\nconfigure do\n  mime_type :foo, 'text\u002Ffoo'\nend\n```\n\nYou can also use it with the `content_type` helper:\n\n```ruby\nget '\u002F' do\n  content_type :foo\n  \"foo foo foo\"\nend\n```\n\n### Generating URLs\n\nFor generating URLs you should use the `url` helper method, for instance, in\nHaml:\n\n```ruby\n%a{:href => url('\u002Ffoo')} foo\n```\n\nIt takes reverse proxies and Rack routers into account - if present.\n\nThis method is also aliased to `to` (see [below](#browser-redirect) for an example).\n\n### Browser Redirect\n\nYou can trigger a browser redirect with the `redirect` helper method:\n\n```ruby\nget '\u002Ffoo' do\n  redirect to('\u002Fbar')\nend\n```\n\nAny additional parameters are handled like arguments passed to `halt`:\n\n```ruby\nredirect to('\u002Fbar'), 303\nredirect 'http:\u002F\u002Fwww.google.com\u002F', 'wrong place, buddy'\n```\n\nYou can also easily redirect back to the page the user came from with\n`redirect back`:\n\n```ruby\nget '\u002Ffoo' do\n  \"\u003Ca href='\u002Fbar'>do something\u003C\u002Fa>\"\nend\n\nget '\u002Fbar' do\n  do_something\n  redirect back\nend\n```\n\nTo pass arguments with a redirect, either add them to the query:\n\n```ruby\nredirect to('\u002Fbar?sum=42')\n```\n\nOr use a session:\n\n```ruby\nenable :sessions\n\nget '\u002Ffoo' do\n  session[:secret] = 'foo'\n  redirect to('\u002Fbar')\nend\n\nget '\u002Fbar' do\n  session[:secret]\nend\n```\n\n### Cache Control\n\nSetting your headers correctly is the foundation for proper HTTP caching.\n\nYou can easily set the Cache-Control header like this:\n\n```ruby\nget '\u002F' do\n  cache_control :public\n  \"cache it!\"\nend\n```\n\nPro tip: Set up caching in a before filter:\n\n```ruby\nbefore do\n  cache_control :public, :must_revalidate, :max_age => 60\nend\n```\n\nIf you are using the `expires` helper to set the corresponding header,\n`Cache-Control` will be set automatically for you:\n\n```ruby\nbefore do\n  expires 500, :public, :must_revalidate\nend\n```\n\nTo properly use caches, you should consider using `etag` or `last_modified`.\nIt is recommended to call those helpers *before* doing any heavy lifting, as\nthey will immediately flush a response if the client already has the current\nversion in its cache:\n\n```ruby\nget \"\u002Farticle\u002F:id\" do\n  @article = Article.find params['id']\n  last_modified @article.updated_at\n  etag @article.sha1\n  erb :article\nend\n```\n\nIt is also possible to use a\n[weak ETag](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FHTTP_ETag#Strong_and_weak_validation):\n\n```ruby\netag @article.sha1, :weak\n```\n\nThese helpers will not do any caching for you, but rather feed the necessary\ninformation to your cache. If you are looking for a quick\nreverse-proxy caching solution, try\n[rack-cache](https:\u002F\u002Fgithub.com\u002Frtomayko\u002Frack-cache#readme):\n\n```ruby\nrequire \"rack\u002Fcache\"\nrequire \"sinatra\"\n\nuse Rack::Cache\n\nget '\u002F' do\n  cache_control :public, :max_age => 36000\n  sleep 5\n  \"hello\"\nend\n```\n\nUse the `:static_cache_control` setting (see [below](#cache-control)) to add\n`Cache-Control` header info to static files.\n\nAccording to RFC 2616, your application should behave differently if the\nIf-Match or If-None-Match header is set to `*`, depending on whether the\nresource requested is already in existence. Sinatra assumes resources for\nsafe (like get) and idempotent (like put) requests are already in existence,\nwhereas other resources (for instance post requests) are treated as new\nresources. You can change this behavior by passing in a `:new_resource`\noption:\n\n```ruby\nget '\u002Fcreate' do\n  etag '', :new_resource => true\n  Article.create\n  erb :new_article\nend\n```\n\nIf you still want to use a weak ETag, pass in a `:kind` option:\n\n```ruby\netag '', :new_resource => true, :kind => :weak\n```\n\n### Sending Files\n\nTo return the contents of a file as the response, you can use the `send_file`\nhelper method:\n\n```ruby\nget '\u002F' do\n  send_file 'foo.png'\nend\n```\n\nIt also takes options:\n\n```ruby\nsend_file 'foo.png', :type => :jpg\n```\n\nThe options are:\n\n\u003Cdl>\n  \u003Cdt>filename\u003C\u002Fdt>\n    \u003Cdd>File name to be used in the response,\n    defaults to the real file name.\u003C\u002Fdd>\n  \u003Cdt>last_modified\u003C\u002Fdt>\n    \u003Cdd>Value for Last-Modified header, defaults to the file's mtime.\u003C\u002Fdd>\n\n  \u003Cdt>type\u003C\u002Fdt>\n    \u003Cdd>Value for Content-Type header, guessed from the file extension if\n    missing.\u003C\u002Fdd>\n\n  \u003Cdt>disposition\u003C\u002Fdt>\n    \u003Cdd>\n      Value for Content-Disposition header, possible values: \u003Ctt>nil\u003C\u002Ftt>\n      (default), \u003Ctt>:attachment\u003C\u002Ftt> and \u003Ctt>:inline\u003C\u002Ftt>\n    \u003C\u002Fdd>\n\n  \u003Cdt>length\u003C\u002Fdt>\n    \u003Cdd>Value for Content-Length header, defaults to file size.\u003C\u002Fdd>\n\n  \u003Cdt>status\u003C\u002Fdt>\n    \u003Cdd>\n      Status code to be sent. Useful when sending a static file as an error\n      page. If supported by the Rack handler, other means than streaming\n      from the Ruby process will be used. If you use this helper method,\n      Sinatra will automatically handle range requests.\n    \u003C\u002Fdd>\n\u003C\u002Fdl>\n\n### Accessing the Request Object\n\nThe incoming request object can be accessed from request level (filter,\nroutes, error handlers) through the `request` method:\n\n```ruby\n# app running on http:\u002F\u002Fexample.com\u002Fexample\nget '\u002Ffoo' do\n  t = %w[text\u002Fcss text\u002Fhtml application\u002Fjavascript]\n  request.accept              # ['text\u002Fhtml', '*\u002F*']\n  request.accept? 'text\u002Fxml'  # true\n  request.preferred_type(t)   # 'text\u002Fhtml'\n  request.body                # request body sent by the client (see below)\n  request.scheme              # \"http\"\n  request.script_name         # \"\u002Fexample\"\n  request.path_info           # \"\u002Ffoo\"\n  request.port                # 80\n  request.request_method      # \"GET\"\n  request.query_string        # \"\"\n  request.content_length      # length of request.body\n  request.media_type          # media type of request.body\n  request.host                # \"example.com\"\n  request.get?                # true (similar methods for other verbs)\n  request.form_data?          # false\n  request[\"some_param\"]       # value of some_param parameter. [] is a shortcut to the params hash.\n  request.referrer            # the referrer of the client or '\u002F'\n  request.user_agent          # user agent (used by :agent condition)\n  request.cookies             # hash of browser cookies\n  request.xhr?                # is this an ajax request?\n  request.url                 # \"http:\u002F\u002Fexample.com\u002Fexample\u002Ffoo\"\n  request.path                # \"\u002Fexample\u002Ffoo\"\n  request.ip                  # client IP address\n  request.secure?             # false (would be true over ssl)\n  request.forwarded?          # true (if running behind a reverse proxy)\n  request.env                 # raw env hash handed in by Rack\nend\n```\n\nSome options, like `script_name` or `path_info`, can also be written:\n\n```ruby\nbefore { request.path_info = \"\u002F\" }\n\nget \"\u002F\" do\n  \"all requests end up here\"\nend\n```\n\nThe `request.body` is an IO or StringIO object:\n\n```ruby\npost \"\u002Fapi\" do\n  request.body.rewind  # in case someone already read it\n  data = JSON.parse request.body.read\n  \"Hello #{data['name']}!\"\nend\n```\n\n### Attachments\n\nYou can use the `attachment` helper to tell the browser the response should\nbe stored on disk rather than displayed in the browser:\n\n```ruby\nget '\u002F' do\n  attachment\n  \"store it!\"\nend\n```\n\nYou can also pass it a file name:\n\n```ruby\nget '\u002F' do\n  attachment \"info.txt\"\n  \"store it!\"\nend\n```\n\n### Dealing with Date and Time\n\nSinatra offers a `time_for` helper method that generates a Time object from\nthe given value. It is also able to convert `DateTime`, `Date` and similar\nclasses:\n\n```ruby\nget '\u002F' do\n  pass if Time.now > time_for('Dec 23, 2016')\n  \"still time\"\nend\n```\n\nThis method is used internally by `expires`, `last_modified` and akin. You\ncan therefore easily extend the behavior of those methods by overriding\n`time_for` in your application:\n\n```ruby\nhelpers do\n  def time_for(value)\n    case value\n    when :yesterday then Time.now - 24*60*60\n    when :tomorrow  then Time.now + 24*60*60\n    else super\n    end\n  end\nend\n\nget '\u002F' do\n  last_modified :yesterday\n  expires :tomorrow\n  \"hello\"\nend\n```\n\n### Looking Up Template Files\n\nThe `find_template` helper is used to find template files for rendering:\n\n```ruby\nfind_template settings.views, 'foo', Tilt[:haml] do |file|\n  puts \"could be #{file}\"\nend\n```\n\nThis is not really useful. But it is useful that you can actually override\nthis method to hook in your own lookup mechanism. For instance, if you want\nto be able to use more than one view directory:\n\n```ruby\nset :views, ['views', 'templates']\n\nhelpers do\n  def find_template(views, name, engine, &block)\n    Array(views).each { |v| super(v, name, engine, &block) }\n  end\nend\n```\n\nAnother example would be using different directories for different engines:\n\n```ruby\nset :views, :haml => 'templates', :default => 'views'\n\nhelpers do\n  def find_template(views, name, engine, &block)\n    _, folder = views.detect { |k,v| engine == Tilt[k] }\n    folder ||= views[:default]\n    super(folder, name, engine, &block)\n  end\nend\n```\n\nYou can also easily wrap this up in an extension and share it with others!\n\nNote that `find_template` does not check if the file really exists but\nrather calls the given block for all possible paths. This is not a\nperformance issue, since `render` will use `break` as soon as a file is\nfound. Also, template locations (and content) will be cached if you are not\nrunning in development mode. You should keep that in mind if you write a\nreally crazy method.\n\n## Configuration\n\nRun once, at startup, in any environment:\n\n```ruby\nconfigure do\n  # setting one option\n  set :option, 'value'\n\n  # setting multiple options\n  set :a => 1, :b => 2\n\n  # same as `set :option, true`\n  enable :option\n\n  # same as `set :option, false`\n  disable :option\n\n  # you can also have dynamic settings with blocks\n  set(:css_dir) { File.join(views, 'css') }\nend\n```\n\nRun only when the environment (`APP_ENV` environment variable) is set to\n`:production`:\n\n```ruby\nconfigure :production do\n  ...\nend\n```\n\nRun when the environment is set to either `:production` or `:test`:\n\n```ruby\nconfigure :production, :test do\n  ...\nend\n```\n\nYou can access those options via `settings`:\n\n```ruby\nconfigure do\n  set :foo, 'bar'\nend\n\nget '\u002F' do\n  settings.foo? # => true\n  settings.foo  # => 'bar'\n  ...\nend\n```\n\n### Configuring attack protection\n\nSinatra is using\n[Rack::Protection](https:\u002F\u002Fgithub.com\u002Fsinatra\u002Fsinatra\u002Ftree\u002Fmain\u002Frack-protection#readme) to\ndefend your application against common, opportunistic attacks. You can\neasily disable this behavior (which will open up your application to tons\nof common vulnerabilities):\n\n```ruby\ndisable :protection\n```\n\nTo skip a single defense layer, set `protection` to an options hash:\n\n```ruby\nset :protection, :except => :path_traversal\n```\nYou can also hand in an array in order to disable a list of protections:\n\n```ruby\nset :protection, :except => [:path_traversal, :remote_token]\n```\n\nBy default, Sinatra will only set up session based protection if `:sessions`\nhave been enabled. See '[Using Sessions](#using-sessions)'. Sometimes you may want to set up\nsessions \"outside\" of the Sinatra app, such as in the config.ru or with a\nseparate `Rack::Builder` instance. In that case, you can still set up session\nbased protection by passing the `:session` option:\n\n```ruby\nset :protection, :session => true\n```\n\n### Available Settings\n\n\u003Cdl>\n  \u003Cdt>absolute_redirects\u003C\u002Fdt>\n    \u003Cdd>\n      If disabled, Sinatra will allow relative redirects, however, Sinatra\n      will no longer conform with RFC 2616 (HTTP 1.1), which only allows\n      absolute redirects.\n    \u003C\u002Fdd>\n    \u003Cdd>\n      Enable if your app is running behind a reverse proxy that has not been\n      set up properly. Note that the \u003Ctt>url\u003C\u002Ftt> helper will still produce\n      absolute URLs, unless you pass in \u003Ctt>false\u003C\u002Ftt> as the second\n      parameter.\n    \u003C\u002Fdd>\n    \u003Cdd>Disabled by default.\u003C\u002Fdd>\n\n  \u003Cdt>add_charset\u003C\u002Fdt>\n    \u003Cdd>\n      Mime types the \u003Ctt>content_type\u003C\u002Ftt> helper will automatically add the\n      charset info to. You should add to it rather than overriding this\n      option: \u003Ctt>settings.add_charset \u003C\u003C \"application\u002Ffoobar\"\u003C\u002Ftt>\n    \u003C\u002Fdd>\n\n  \u003Cdt>app_file\u003C\u002Fdt>\n    \u003Cdd>\n      Path to the main application file, used to detect project root, views\n      and public folder and inline templates.\n    \u003C\u002Fdd>\n\n  \u003Cdt>bind\u003C\u002Fdt>\n    \u003Cdd>\n      IP address to bind to (default: \u003Ctt>0.0.0.0\u003C\u002Ftt> \u003Cem>or\u003C\u002Fem>\n      \u003Ctt>localhost\u003C\u002Ftt> if your `environment` is set to development). Only\n      used for built-in server.\n    \u003C\u002Fdd>\n\n  \u003Cdt>default_content_type\u003C\u002Fdt>\n  \u003Cdd>\n    Content-Type to assume if unknown (defaults to \u003Ctt>\"text\u002Fhtml\"\u003C\u002Ftt>). Set\n    to \u003Ctt>nil\u003C\u002Ftt> to not set a default Content-Type on every response; when\n    configured so, you must set the Content-Type manually when emitting content\n    or the user-agent will have to sniff it (or, if \u003Ctt>nosniff\u003C\u002Ftt> is enabled\n    in Rack::Protection::XSSHeader, assume \u003Ctt>application\u002Foctet-stream\u003C\u002Ftt>).\n  \u003C\u002Fdd>\n\n  \u003Cdt>default_encoding\u003C\u002Fdt>\n    \u003Cdd>Encoding to assume if unknown (defaults to \u003Ctt>\"utf-8\"\u003C\u002Ftt>).\u003C\u002Fdd>\n\n  \u003Cdt>dump_errors\u003C\u002Fdt>\n    \u003Cdd>Display errors in the log. Enabled by default unless environment is \"test\".\u003C\u002Fdd>\n\n  \u003Cdt>environment\u003C\u002Fdt>\n    \u003Cdd>\n      Current environment. Defaults to \u003Ctt>ENV['APP_ENV']\u003C\u002Ftt>, or\n      \u003Ctt>\"development\"\u003C\u002Ftt> if not available.\n    \u003C\u002Fdd>\n\n  \u003Cdt>host_authorization\u003C\u002Fdt>\n  \u003Cdd>\n    \u003Cp>\n      You can pass a hash of options to \u003Ctt>host_authorization\u003C\u002Ftt>,\n      to be used by the \u003Ctt>Rack::Protection::HostAuthorization\u003C\u002Ftt> middleware.\n    \u003C\u002Fp>\n    \u003Cp>\n      The middleware can block requests with unrecognized hostnames, to prevent DNS rebinding\n      and other host header attacks. It checks the \u003Ctt>Host\u003C\u002Ftt>, \u003Ctt>X-Forwarded-Host\u003C\u002Ftt>\n      and \u003Ctt>Forwarded\u003C\u002Ftt> headers.\n    \u003C\u002Fp>\n    \u003Cp>\n      Useful options are:\n      \u003Cul>\n        \u003Cli>\u003Ctt>permitted_hosts\u003C\u002Ftt> – an array of hostnames (and \u003Ctt>IPAddr\u003C\u002Ftt> objects) your app recognizes\n          \u003Cul>\n            \u003Cli>in the \u003Ctt>development\u003C\u002Ftt> environment, it is set to \u003Ctt>.localhost\u003C\u002Ftt>, \u003Ctt>.test\u003C\u002Ftt> and any IPv4\u002FIPv6 address\u003C\u002Fli>\n            \u003Cli>if empty, any hostname is permitted (the default for any other environment)\u003C\u002Fli>\n          \u003C\u002Ful>\n        \u003C\u002Fli>\n        \u003Cli>\u003Ctt>status\u003C\u002Ftt> – the HTTP status code used in the response when a request is blocked (defaults to \u003Ctt>403\u003C\u002Ftt>)\u003C\u002Fli>\n        \u003Cli>\u003Ctt>message\u003C\u002Ftt> – the body used in the response when a request is blocked (defaults to \u003Ctt>Host not permitted\u003C\u002Ftt>)\u003C\u002Fli>\n        \u003Cli>\u003Ctt>allow_if\u003C\u002Ftt> – supply a \u003Ctt>Proc\u003C\u002Ftt> to use custom allow\u002Fdeny logic, the proc is passed the request environment\u003C\u002Fli>\n      \u003C\u002Ful>\n    \u003C\u002Fp>\n  \u003C\u002Fdd>\n\n  \u003Cdt>logging\u003C\u002Fdt>\n    \u003Cdd>Use the logger.\u003C\u002Fdd>\n\n  \u003Cdt>lock\u003C\u002Fdt>\n    \u003Cdd>\n      Places a lock around every request, only running processing on request\n      per Ruby process concurrently.\n    \u003C\u002Fdd>\n    \u003Cdd>Enabled if your app is not thread-safe. Disabled by default.\u003C\u002Fdd>\n\n  \u003Cdt>method_override\u003C\u002Fdt>\n    \u003Cdd>\n      Use \u003Ctt>_method\u003C\u002Ftt> magic to allow put\u002Fdelete forms in browsers that\n      don't support it.\n    \u003C\u002Fdd>\n\n  \u003Cdt>mustermann_opts\u003C\u002Fdt>\n  \u003Cdd>\n    A default hash of options to pass to Mustermann.new when compiling routing\n    paths.\n  \u003C\u002Fdd>\n\n  \u003Cdt>port\u003C\u002Fdt>\n    \u003Cdd>Port to listen on. Only used for built-in server.\u003C\u002Fdd>\n\n  \u003Cdt>prefixed_redirects\u003C\u002Fdt>\n    \u003Cdd>\n      Whether or not to insert \u003Ctt>request.script_name\u003C\u002Ftt> into redirects\n      if no absolute path is given. That way \u003Ctt>redirect '\u002Ffoo'\u003C\u002Ftt> would\n        behave like \u003Ctt>redirect to('\u002Ffoo')\u003C\u002Ftt>. Disabled by default.\n    \u003C\u002Fdd>\n\n  \u003Cdt>protection\u003C\u002Fdt>\n    \u003Cdd>\n      Whether or not to enable web attack protections. See protection section\n      above.\n    \u003C\u002Fdd>\n\n  \u003Cdt>public_dir\u003C\u002Fdt>\n    \u003Cdd>Alias for \u003Ctt>public_folder\u003C\u002Ftt>. See below.\u003C\u002Fdd>\n\n  \u003Cdt>public_folder\u003C\u002Fdt>\n    \u003Cdd>\n      Path to the folder public files are served from. Only used if static\n      file serving is enabled (see \u003Ctt>static\u003C\u002Ftt> setting below). Inferred\n      from \u003Ctt>app_file\u003C\u002Ftt> setting if not set.\n    \u003C\u002Fdd>\n\n  \u003Cdt>quiet\u003C\u002Fdt>\n    \u003Cdd>\n      Disables logs generated by Sinatra's start and stop commands.\n      \u003Ctt>false\u003C\u002Ftt> by default.\n    \u003C\u002Fdd>\n\n  \u003Cdt>reload_templates\u003C\u002Fdt>\n    \u003Cdd>\n      Whether or not to reload templates between requests. Enabled in\n      development mode.\n    \u003C\u002Fdd>\n\n  \u003Cdt>root\u003C\u002Fdt>\n    \u003Cdd>\n      Path to project root folder. Inferred from \u003Ctt>app_file\u003C\u002Ftt> setting\n      if not set.\n    \u003C\u002Fdd>\n\n  \u003Cdt>raise_errors\u003C\u002Fdt>\n    \u003Cdd>\n      Raise unhandled errors (will stop application). Enabled by default when\n      \u003Ctt>environment\u003C\u002Ftt> is set to \u003Ctt>\"test\"\u003C\u002Ftt>, disabled otherwise.\n    \u003C\u002Fdd>\n    \u003Cdd>\n      Any explicitly defined error handlers always override this setting. See \n      the \"Error\" section below.\n    \u003C\u002Fdd>\n\n  \u003Cdt>run\u003C\u002Fdt>\n    \u003Cdd>\n      If enabled, Sinatra will handle starting the web server. Do not\n      enable if using rackup or other means.\n    \u003C\u002Fdd>\n\n  \u003Cdt>running\u003C\u002Fdt>\n    \u003Cdd>Is the built-in server running now? Do not change this setting!\u003C\u002Fdd>\n\n  \u003Cdt>server\u003C\u002Fdt>\n    \u003Cdd>\n      Server or list of servers to use for built-in server. Order indicates\n      priority, default depends on Ruby implementation.\n    \u003C\u002Fdd>\n\n  \u003Cdt>server_settings\u003C\u002Fdt>\n    \u003Cdd>\n      You can pass a hash of options to \u003Ctt>server_settings\u003C\u002Ftt>,\n      such as \u003Ctt>Host\u003C\u002Ftt> or \u003Ctt>Port\u003C\u002Ftt>.\n    \u003C\u002Fdd>\n\n  \u003Cdt>sessions\u003C\u002Fdt>\n    \u003Cdd>\n      Enable cookie-based sessions support using\n      \u003Ctt>Rack::Session::Cookie\u003C\u002Ftt>. See 'Using Sessions' section for more\n      information.\n    \u003C\u002Fdd>\n\n  \u003Cdt>session_store\u003C\u002Fdt>\n    \u003Cdd>\n      The Rack session middleware used. Defaults to\n      \u003Ctt>Rack::Session::Cookie\u003C\u002Ftt>. See 'Using Sessions' section for more\n      information.\n    \u003C\u002Fdd>\n\n  \u003Cdt>show_exceptions\u003C\u002Fdt>\n    \u003Cdd>\n      Show a stack trace in the browser when an exception happens. Enabled by\n      default when \u003Ctt>environment\u003C\u002Ftt> is set to \u003Ctt>\"development\"\u003C\u002Ftt>,\n      disabled otherwise.\n    \u003C\u002Fdd>\n    \u003Cdd>\n      Can also be set to \u003Ctt>:after_handler\u003C\u002Ftt> to trigger app-specified\n      error handling before showing a stack trace in the browser.\n    \u003C\u002Fdd>\n\n  \u003Cdt>static\u003C\u002Fdt>\n    \u003Cdd>Whether Sinatra should handle serving static files.\u003C\u002Fdd>\n    \u003Cdd>Disable when using a server able to do this on its own.\u003C\u002Fdd>\n    \u003Cdd>Disabling will boost performance.\u003C\u002Fdd>\n    \u003Cdd>\n      Enabled by default in classic style, disabled for modular apps.\n    \u003C\u002Fdd>\n\n  \u003Cdt>static_cache_control\u003C\u002Fdt>\n    \u003Cdd>\n      When Sinatra is serving static files, set this to add\n      \u003Ctt>Cache-Control\u003C\u002Ftt> headers to the responses. Uses the\n      \u003Ctt>cache_control\u003C\u002Ftt> helper. Disabled by default.\n    \u003C\u002Fdd>\n    \u003Cdd>\n      Use an explicit array when setting multiple values:\n      \u003Ctt>set :static_cache_control, [:public, :max_age => 300]\u003C\u002Ftt>\n    \u003C\u002Fdd>\n\n  \u003Cdt>static_headers\u003C\u002Fdt>\n    \u003Cdd>\n      Allows you to define custom header settings for static file responses.\n    \u003C\u002Fdd>\n    \u003Cdd>\n      For example: \u003Cbr>\n      \u003Ctt>set :static_headers, {'access-control-allow-origin' => '*', 'x-static-asset' => 'served-by-sinatra'}\u003C\u002Ftt>\n    \u003C\u002Fdd>\n\n\n  \u003Cdt>threaded\u003C\u002Fdt>\n    \u003Cdd>\n      If set to \u003Ctt>true\u003C\u002Ftt>, will tell server to use\n      \u003Ctt>EventMachine.defer\u003C\u002Ftt> for processing the request.\n    \u003C\u002Fdd>\n\n  \u003Cdt>traps\u003C\u002Fdt>\n    \u003Cdd>Whether Sinatra should handle system signals.\u003C\u002Fdd>\n\n  \u003Cdt>views\u003C\u002Fdt>\n    \u003Cdd>\n      Path to the views folder. Inferred from \u003Ctt>app_file\u003C\u002Ftt> setting if\n      not set.\n    \u003C\u002Fdd>\n\n  \u003Cdt>x_cascade\u003C\u002Fdt>\n    \u003Cdd>\n      Whether or not to set the X-Cascade header if no route matches.\n      Defaults to \u003Ctt>true\u003C\u002Ftt>.\n    \u003C\u002Fdd>\n\u003C\u002Fdl>\n\n## Lifecycle Events\n\nThere are 2 lifecycle events currently exposed by Sinatra. One when the server starts and one when it stops.\n\nThey can be used like this:\n\n```ruby\non_start do\n  puts \"===== Booting up =====\"\nend\n\non_stop do\n  puts \"===== Shutting down =====\"\nend\n```\n\nNote that these callbacks only work when using Sinatra to start the web server.\n\n## Environments\n\nThere are three predefined `environments`: `\"development\"`,\n`\"production\"` and `\"test\"`. Environments can be set through the\n`APP_ENV` environment variable. The default value is `\"development\"`.\nIn the `\"development\"` environment all templates are reloaded between\nrequests, and special `not_found` and `error` handlers display stack\ntraces in your browser. In the `\"production\"` and `\"test\"` environments,\ntemplates are cached by default.\n\nTo run different environments, set the `APP_ENV` environment variable:\n\n```shell\nAPP_ENV=production ruby my_app.rb\n```\n\nYou can use predefined methods: `development?`, `test?` and `production?` to\ncheck the current environment setting:\n\n```ruby\nget '\u002F' do\n  if settings.development?\n    \"development!\"\n  else\n    \"not development!\"\n  end\nend\n```\n\n## Error Handling\n\nError handlers run within the same context as routes and before filters,\nwhich means you get all the goodies it has to offer, like `haml`, `erb`,\n`halt`, etc.\n\n### Not Found\n\nWhen a `Sinatra::NotFound` exception is raised, or the response's status\ncode is 404, the `not_found` handler is invoked:\n\n```ruby\nnot_found do\n  'This is nowhere to be found.'\nend\n```\n\n### Error\n\nThe `error` handler is invoked any time an exception is raised from a route\nblock or a filter. But note in development it will only run if you set the\nshow exceptions option to `:after_handler`:\n\n```ruby\nset :show_exceptions, :after_handler\n```\n\nA catch-all error handler can be defined with `error` and a block:\n\n```ruby\nerror do\n  'Sorry there was a nasty error'\nend\n```\n\nThe exception object can be obtained from the `sinatra.error` Rack variable:\n\n```ruby\nerror do\n  'Sorry there was a nasty error - ' + env['sinatra.error'].message\nend\n```\n\nPass an error class as an argument to create handlers for custom errors:\n\n```ruby\nerror MyCustomError do\n  'So what happened was...' + env['sinatra.error'].message\nend\n```\n\nThen, if this happens:\n\n```ruby\nget '\u002F' do\n  raise MyCustomError, 'something bad'\nend\n```\n\nYou get this:\n\n```\nSo what happened was... something bad\n```\n\nAlternatively, you can install an error handler for a status code:\n\n```ruby\nerror 403 do\n  'Access forbidden'\nend\n\nget '\u002Fsecret' do\n  403\nend\n```\n\nOr a range:\n\n```ruby\nerror 400..510 do\n  'Boom'\nend\n```\n\nSinatra installs special `not_found` and `error` handlers when\nrunning under the development environment to display nice stack traces\nand additional debugging information in your browser.\n\n### Behavior with `raise_errors` option\n\nWhen `raise_errors` option is `true`, errors that are unhandled are raised \noutside of the application. Additionally, any errors that would have been \ncaught by the catch-all error handler are raised.\n\nFor example, consider the following configuration:\n\n```ruby\n# First handler\nerror MyCustomError do\n  'A custom message'\nend\n\n# Second handler\nerror do\n  'A catch-all message'\nend\n```\n\nIf `raise_errors` is `false`:\n\n* When `MyCustomError` or descendant is raised, the first handler is invoked.\n  The HTTP response body will contain `\"A custom message\"`.\n* When any other error is raised, the second handler is invoked. The HTTP \n  response body will contain `\"A catch-all message\"`.\n\nIf `raise_errors` is `true`:\n\n* When `MyCustomError` or descendant is raised, the behavior is identical to \n  when `raise_errors` is `false`, described above.\n* When any other error is raised, the second handler is *not* invoked, and \n  the error is raised outside of the application.\n  * If the environment is `production`, the HTTP response body will contain \n    a generic error message, e.g. `\"An unhandled lowlevel error occurred. The\n    application logs may have details.\"`\n  * If the environment is not `production`, the HTTP response body will contain\n    the verbose error backtrace.\n  * Regardless of environment, if `show_exceptions` is set to `:after_handler`, \n    the HTTP response body will contain the verbose error backtrace.\n\nIn the `test` environment, `raise_errors` is set to `true` by default. This \nmeans that in order to write a test for a catch-all error handler, \n`raise_errors` must temporarily be set to `false` for that particular test.\n\n## Rack Middleware\n\nSinatra rides on [Rack](https:\u002F\u002Frack.github.io\u002F), a minimal standard\ninterface for Ruby web frameworks. One of Rack's most interesting\ncapabilities for application developers is support for \"middleware\" --\ncomponents that sit between the server and your application monitoring\nand\u002For manipulating the HTTP request\u002Fresponse to provide various types\nof common functionality.\n\nSinatra makes building Rack middleware pipelines a cinch via a top-level\n`use` method:\n\n```ruby\nrequire 'sinatra'\nrequire 'my_custom_middleware'\n\nuse Rack::Lint\nuse MyCustomMiddleware\n\nget '\u002Fhello' do\n  'Hello World'\nend\n```\n\nThe semantics of `use` are identical to those defined for the\n[Rack::Builder](https:\u002F\u002Fwww.rubydoc.info\u002Fgithub\u002Frack\u002Frack\u002Fmain\u002FRack\u002FBuilder) DSL\n(most frequently used from rackup files). For example, the `use` method\naccepts multiple\u002Fvariable args as well as blocks:\n\n```ruby\nuse Rack::Auth::Basic do |username, password|\n  username == 'admin' && password == 'secret'\nend\n```\n\nRack is distributed with a variety of standard middleware for logging,\ndebugging, URL routing, authentication, and session handling. Sinatra uses\nmany of these components automatically based on configuration so you\ntypically don't have to `use` them explicitly.\n\nYou can find useful middleware in\n[rack](https:\u002F\u002Fgithub.com\u002Frack\u002Frack\u002Ftree\u002Fmain\u002Flib\u002Frack),\n[rack-contrib](https:\u002F\u002Fgithub.com\u002Frack\u002Frack-contrib#readme),\nor in the [Rack wiki](https:\u002F\u002Fgithub.com\u002Frack\u002Frack\u002Fwiki\u002FList-of-Middleware).\n\n## Testing\n\nSinatra tests can be written using any Rack-based testing library or\nframework.\n[Rack::Test](https:\u002F\u002Fwww.rubydoc.info\u002Fgithub\u002Frack\u002Frack-test\u002Fmain\u002Fframes)\nis recommended:\n\n```ruby\nrequire 'my_sinatra_app'\nrequire 'minitest\u002Fautorun'\nrequire 'rack\u002Ftest'\n\nclass MyAppTest \u003C Minitest::Test\n  include Rack::Test::Methods\n\n  def app\n    Sinatra::Application\n  end\n\n  def test_my_default\n    get '\u002F'\n    assert_equal 'Hello World!', last_response.body\n  end\n\n  def test_with_params\n    get '\u002Fmeet', :name => 'Frank'\n    assert_equal 'Hello Frank!', last_response.body\n  end\n\n  def test_with_user_agent\n    get '\u002F', {}, 'HTTP_USER_AGENT' => 'Songbird'\n    assert_equal \"You're using Songbird!\", last_response.body\n  end\nend\n```\n\nNote: If you are using Sinatra in the modular style, replace\n`Sinatra::Application` above with the class name of your app.\n\n## Sinatra::Base - Middleware, Libraries, and Modular Apps\n\nDefining your app at the top-level works well for micro-apps but has\nconsiderable drawbacks when building reusable components such as Rack\nmiddleware, Rails metal, simple libraries with a server component, or even\nSinatra extensions. The top-level assumes a micro-app style configuration\n(e.g., a single application file, `.\u002Fpublic` and `.\u002Fviews`\ndirectories, logging, exception detail page, etc.). That's where\n`Sinatra::Base` comes into play:\n\n```ruby\nrequire 'sinatra\u002Fbase'\n\nclass MyApp \u003C Sinatra::Base\n  set :sessions, true\n  set :foo, 'bar'\n\n  get '\u002F' do\n    'Hello world!'\n  end\nend\n```\n\nThe methods available to `Sinatra::Base` subclasses are exactly the same\nas those available via the top-level DSL. Most top-level apps can be\nconverted to `Sinatra::Base` components with two modifications:\n\n* Your file should require `sinatra\u002Fbase` instead of `sinatra`;\n  otherwise, all of Sinatra's DSL methods are imported into the main\n  namespace.\n* Put your app's routes, error handlers, filters, and options in a subclass\n  of `Sinatra::Base`.\n\n`Sinatra::Base` is a blank slate. Most options are disabled by default,\nincluding the built-in server. See [Configuring\nSettings](http:\u002F\u002Fwww.sinatrarb.com\u002Fconfiguration.html) for details on\navailable options and their behavior. If you want behavior more similar\nto when you define your app at the top level (also known as Classic\nstyle), you can subclass `Sinatra::Application`:\n\n```ruby\nrequire 'sinatra\u002Fbase'\n\nclass MyApp \u003C Sinatra::Application\n  get '\u002F' do\n    'Hello world!'\n  end\nend\n```\n\n### Modular vs. Classic Style\n\nContrary to common belief, there is nothing wrong with the classic\nstyle. If it suits your application, you do not have to switch to a\nmodular application.\n\nThe main disadvantage of using the classic style rather than the modular\nstyle is that you will only have one Sinatra application per Ruby\nprocess. If you plan to use more than one, switch to the modular style.\nThere is no reason you cannot mix the modular and classic styles.\n\nIf switching from one style to the other, you should be aware of\nslightly different default settings:\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Cth>Setting\u003C\u002Fth>\n    \u003Cth>Classic\u003C\u002Fth>\n    \u003Cth>Modular\u003C\u002Fth>\n    \u003Cth>Modular\u003C\u002Fth>\n  \u003C\u002Ftr>\n\n  \u003Ctr>\n    \u003Ctd>app_file\u003C\u002Ftd>\n    \u003Ctd>file loading sinatra\u003C\u002Ftd>\n    \u003Ctd>file subclassing Sinatra::Base\u003C\u002Ftd>\n    \u003Ctd>file subclassing Sinatra::Application\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\n  \u003Ctr>\n    \u003Ctd>run\u003C\u002Ftd>\n    \u003Ctd>$0 == app_file\u003C\u002Ftd>\n    \u003Ctd>false\u003C\u002Ftd>\n    \u003Ctd>false\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\n  \u003Ctr>\n    \u003Ctd>logging\u003C\u002Ftd>\n    \u003Ctd>true\u003C\u002Ftd>\n    \u003Ctd>false\u003C\u002Ftd>\n    \u003Ctd>true\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\n  \u003Ctr>\n    \u003Ctd>method_override\u003C\u002Ftd>\n    \u003Ctd>true\u003C\u002Ftd>\n    \u003Ctd>false\u003C\u002Ftd>\n    \u003Ctd>true\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\n  \u003Ctr>\n    \u003Ctd>inline_templates\u003C\u002Ftd>\n    \u003Ctd>true\u003C\u002Ftd>\n    \u003Ctd>false\u003C\u002Ftd>\n    \u003Ctd>true\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\n  \u003Ctr>\n    \u003Ctd>static\u003C\u002Ftd>\n    \u003Ctd>true\u003C\u002Ftd>\n    \u003Ctd>File.exist?(public_folder)\u003C\u002Ftd>\n    \u003Ctd>true\u003C\u002Ftd>\n  \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n### Serving a Modular Application\n\nThere are two common options for starting a modular app, actively\nstarting with `run!`:\n\n```ruby\n# my_app.rb\nrequire 'sinatra\u002Fbase'\n\nclass MyApp \u003C Sinatra::Base\n  # ... app code here ...\n\n  # start the server if ruby file executed directly\n  run! if app_file == $0\nend\n```\n\nStart with:\n\n```shell\nruby my_app.rb\n```\n\nOr with a `config.ru` file, which allows using any Rack handle","Sinatra 是一个基于 Ruby 的轻量级 Web 开发框架，通过简洁的 DSL（领域特定语言）帮助开发者快速构建 Web 应用。其核心功能包括路由定义、条件处理、多种模板引擎支持以及静态文件服务等，使得应用开发既高效又灵活。Sinatra 适合用于创建小型到中型规模的 Web 项目，尤其是当需要快速原型设计或构建 RESTful API 时。由于其低学习曲线和对 Ruby 生态系统的良好集成，无论是初学者还是有经验的开发者都能轻松上手使用 Sinatra。",2,"2026-06-11 03:13:30","top_language"]