Read From a File in Public Into Sinatra File

This page is as well available in Chinese, French, German language, Hungarian, Korean, Portuguese (Brazilian), Portuguese (European), Russian, Spanish and Japanese.

Getting Started

Gem Version Build Status SemVer

Sinatra is a DSL for chop-chop creating web applications in Ruby with minimal effort:

                          # myapp.rb              require              'sinatra'              get              '/'              do              'Howdy world!'              terminate                      

Install the gem:

And run with:

View at: http://localhost:4567

The code you changed will non take upshot until you restart the server. Please restart the server every time you lot modify or apply sinatra/reloader.

It is recommended to also run gem install thin, which Sinatra volition pick upwardly if available.

Routes

In Sinatra, a route is an HTTP method paired with a URL-matching pattern. Each route is associated with a block:

                          get              '/'              do              .              .              testify              something              .              .              end              mail              '/'              exercise              .              .              create              something              .              .              end              put              '/'              do              .              .              replace              something              .              .              end              patch              '/'              do              .              .              modify              something              .              .              end              delete              '/'              do              .              .              demolish              something              .              .              end              options              '/'              do              .              .              appease              something              .              .              cease              link              '/'              practise              .              .              affiliate              something              .              .              end              unlink              '/'              do              .              .              separate              something              .              .              finish                      

Routes are matched in the order they are divers. The get-go route that matches the asking is invoked.

Routes with abaft slashes are different from the ones without:

                          get              '/foo'              do              # Does not match "GET /foo/"              end                      

Route patterns may include named parameters, attainable via the params hash:

                          get              '/hello/:name'              exercise              # matches "GET /how-do-you-do/foo" and "GET /hello/bar"              # params['name'] is 'foo' or 'bar'              "Hello                            #{              params              [              'name'              ]              }              !"              end                      

You can too access named parameters via block parameters:

                          go              '/hello/:proper name'              do              |              north              |              # matches "Get /hello/foo" and "Go /hello/bar"              # params['name'] is 'foo' or 'bar'              # due north stores params['proper name']              "Hi                            #{              northward              }              !"              finish                      

Route patterns may also include splat (or wildcard) parameters, accessible via the params['splat'] array:

                          become              '/say/*/to/*'              do              # matches /say/hello/to/world              params              [              'splat'              ]              # => ["hullo", "earth"]              stop              get              '/download/*.*'              practice              # matches /download/path/to/file.xml              params              [              'splat'              ]              # => ["path/to/file", "xml"]              end                      

Or with cake parameters:

                          get              '/download/*.*'              do              |              path              ,              ext              |              [              path              ,              ext              ]              # => ["path/to/file", "xml"]              end                      

Route matching with Regular Expressions:

                          get              /\/how-do-you-do\/([\w]+)/              do              "Hello,                            #{              params              [              'captures'              ].              first              }              !"              end                      

Or with a cake parameter:

                          get              %r{/hello/([              \w              ]+)}              do              |              c              |              # Matches "Become /meta/howdy/world", "Become /howdy/world/1234" etc.              "Hello,                            #{              c              }              !"              cease                      

Route patterns may have optional parameters:

                          become              '/posts/:format?'              do              # matches "GET /posts/" and whatever extension "GET /posts/json", "GET /posts/xml" etc              finish                      

Routes may also utilize query parameters:

                          get              '/posts'              do              # matches "GET /posts?title=foo&author=bar"              title              =              params              [              'title'              ]              writer              =              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 (run across beneath), the request path might exist modified earlier matching confronting your routes.

You may customize the Mustermann options used for a given route past passing in a :mustermann_opts hash:

                          get              '\A/posts\z'              ,              :mustermann_opts              =>              {              :type              =>              :regexp              ,              :check_anchors              =>              simulated              }              do              # matches /posts exactly, with explicit anchoring              "If you lot match an anchored pattern handclapping your hands!"              end                      

Information technology looks similar a condition, but it isn't i! These options volition be merged into the global :mustermann_opts hash described below.

Conditions

Routes may include a variety of matching conditions, such as the user agent:

                          get              '/foo'              ,              :agent              =>              /Songbird (\d\.\d)[\d\/]*?/              exercise              "You're using Songbird version                            #{              params              [              'agent'              ][              0              ]              }              "              end              get              '/foo'              do              # Matches non-songbird browsers              stop                      

Other bachelor conditions are host_name and provides:

                          get              '/'              ,              :host_name              =>              /^admin\./              do              "Admin Area, Access denied!"              stop              get              '/'              ,              :provides              =>              'html'              do              haml              :index              end              become              '/'              ,              :provides              =>              [              'rss'              ,              'atom'              ,              'xml'              ]              do              builder              :feed              finish                      

provides searches the request'south Accept header.

You can easily define your own weather:

                          ready              (              :probability              )              {              |              value              |              status              {              rand              <=              value              }              }              go              '/win_a_car'              ,              :probability              =>              0              .              1              do              "You won!"              end              get              '/win_a_car'              practice              "Sorry, you lost."              end                      

For a condition that takes multiple values use a splat:

                          fix              (              :auth              )              do              |*              roles              |              # <- find the splat here              condition              practise              unless              logged_in?              &&              roles              .              any?              {              |              function              |              current_user              .              in_role?              part              }              redirect              "/login/"              ,              303              cease              end              end              get              "/my/account/"              ,              :auth              =>              [              :user              ,              :admin              ]              practice              "Your Account Details"              end              become              "/only/admin/"              ,              :auth              =>              :admin              do              "But admins are allowed here!"              end                      

Return Values

The return value of a route cake determines at to the lowest degree the response torso passed on to the HTTP client, or at least the adjacent middleware in the Rack stack. Nigh commonly, this is a cord, as in the above examples. But other values are as well accepted.

You can return any object that would either exist a valid Rack response, Rack body object or HTTP status code:

  • An Array with iii 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 condition code

That mode we can, for instance, hands implement a streaming example:

                          class              Stream              def              each              100              .              times              {              |              i              |              yield              "              #{              i              }              \n              "              }              end              finish              get              (              '/'              )              {              Stream              .              new              }                      

Yous can also apply the stream helper method (described beneath) to reduce banality plate and embed the streaming logic in the route.

Custom Road Matchers

Equally shown higher up, Sinatra ships with built-in support for using String patterns and regular expressions as route matches. However, it does not stop there. You tin easily define your own matchers:

                          class              AllButPattern              Match              =              Struct              .              new              (              :captures              )              def              initialize              (              except              )              @except              =              except              @captures              =              Match              .              new              ([])              end              def              friction match              (              str              )              @captures              unless              @except              ===              str              terminate              cease              def              all_but              (              design              )              AllButPattern              .              new              (              pattern              )              end              go              all_but              (              "/index"              )              do              # ...              terminate                      

Annotation that the in a higher place example might be over-engineered, every bit it tin also be expressed every bit:

                          get              //              do              laissez passer              if              asking              .              path_info              ==              "/index"              # ...              end                      

Or, using negative expect ahead:

                          get              %r{(?!/alphabetize)}              practise              # ...              end                      

Static Files

Static files are served from the ./public directory. Y'all can specify a different location past setting the :public_folder pick:

                          set              :public_folder              ,              __dir__              +              '/static'                      

Note that the public directory name is not included in the URL. A file ./public/css/way.css is made available equally http://case.com/css/style.css.

Apply the :static_cache_control setting (see below) to add together Enshroud-Command header info.

Views / Templates

Each template linguistic communication is exposed via its own rendering method. These methods simply render a string:

                          go              '/'              do              erb              :index              end                      

This renders views/alphabetize.erb.

Instead of a template name, you can also just laissez passer in the template content directly:

                          become              '/'              practice              lawmaking              =              "<%= Time.now %>"              erb              code              terminate                      

Templates accept a 2nd argument, the options hash:

                          go              '/'              do              erb              :index              ,              :layout              =>              :post              cease                      

This will render views/index.erb embedded in the views/mail.erb (default is views/layout.erb, if it exists).

Whatsoever options non understood by Sinatra will be passed on to the template engine:

                          become              '/'              exercise              haml              :index              ,              :format              =>              :html5              terminate                      

You tin can also set options per template language in general:

                          prepare              :haml              ,              :format              =>              :html5              get              '/'              practice              haml              :alphabetize              stop                      

Options passed to the render method override options ready via fix.

Available Options:

locals
List of locals passed to the certificate. Handy with partials. Example: erb "<%= foo %>", :locals => {:foo => "bar"}
default_encoding
String encoding to use if uncertain. Defaults to settings.default_encoding.
views
Views folder to load templates from. Defaults to settings.views.
layout
Whether to use a layout (true or false). If it'due south a Symbol, specifies what template to employ. Example: erb :index, :layout => !asking.xhr?
content_type
Content-Blazon the template produces. Default depends on template language.
telescopic
Telescopic to render template under. Defaults to the awarding instance. If y'all change this, instance variables and helper methods will not be available.
layout_engine
Template engine to utilize for rendering the layout. Useful for languages that do not back up layouts otherwise. Defaults to the engine used for the template. Case: fix :rdoc, :layout_engine => :erb
layout_options
Special options just used for rendering the layout. Example: set :rdoc, :layout_options => { :views => 'views/layouts' }

Templates are assumed to exist located directly under the ./views directory. To use a different views directory:

                          set up              :views              ,              settings              .              root              +              '/templates'                      

Ane of import thing to remember is that you ever take to reference templates with symbols, even if they're in a subdirectory (in this case, use: :'subdir/template' or 'subdir/template'.to_sym). You lot must use a symbol because otherwise rendering methods will render whatsoever strings passed to them straight.

Literal Templates

                          get              '/'              do              haml              '%div.championship Hi World'              end                      

Renders the template string. Y'all can optionally specify :path and :line for a clearer backtrace if in that location is a filesystem path or line associated with that cord:

                          get              '/'              do              haml              '%div.title Hello World'              ,              :path              =>              'examples/file.haml'              ,              :line              =>              3              terminate                      

Available Template Languages

Some languages have multiple implementations. To specify what implementation to use (and to be thread-safe), you should simply crave information technology starting time:

                          require              'rdiscount'              # or crave 'bluecloth'              become              (              '/'              )              {              markdown              :index              }                      

Haml Templates

Dependency haml
File Extension .haml
Example haml :index, :format => :html5

Erb Templates

Dependency erubi or erubis or erb (included in Cherry-red)
File Extensions .erb, .rhtml or .erubi (Erubi simply) or .erubis (Erubis just)
Example erb :index

Builder Templates

Dependency builder
File Extension .builder
Example builder { |xml| xml.em "hi" }

It also takes a block for inline templates (run across example).

Nokogiri Templates

Dependency nokogiri
File Extension .nokogiri
Example nokogiri { |xml| xml.em "hi" }

It also takes a block for inline templates (run across example).

Sass Templates

Dependency sass
File Extension .sass
Example sass :stylesheet, :style => :expanded

SCSS Templates

Dependency sass
File Extension .scss
Example scss :stylesheet, :style => :expanded

Less Templates

Dependency less
File Extension .less
Example less :stylesheet

Liquid Templates

Dependency liquid
File Extension .liquid
Example liquid :index, :locals => { :central => 'value' }

Since you cannot call Ruby methods (except for yield) from a Liquid template, you almost always desire to pass locals to it.

Markdown Templates

Information technology is not possible to call methods from Markdown, nor to laissez passer locals to information technology. You therefore will usually use it in combination with another rendering engine:

                          erb              :overview              ,              :locals              =>              {              :text              =>              markdown              (              :introduction              )              }                      

Note that yous may also call the markdown method from within other templates:

                          %              h1              Hello              From              Haml              !              %              p              =              markdown              (              :greetings              )                      

Since y'all cannot telephone call Ruby from Markdown, you cannot use layouts written in Markdown. However, it is possible to use another rendering engine for the template than for the layout by passing the :layout_engine pick.

Textile Templates

Dependency RedCloth
File Extension .material
Example cloth :index, :layout_engine => :erb

Information technology is not possible to telephone call methods from Fabric, nor to pass locals to it. You therefore volition usually use it in combination with another rendering engine:

                          erb              :overview              ,              :locals              =>              {              :text              =>              textile              (              :introduction              )              }                      

Note that you lot may also call the textile method from within other templates:

                          %              h1              How-do-you-do              From              Haml              !              %              p              =              textile              (              :greetings              )                      

Since y'all cannot call Ruby-red from Textile, you cannot use layouts written in Textile. Yet, it is possible to utilize another rendering engine for the template than for the layout past passing the :layout_engine option.

RDoc Templates

Dependency RDoc
File Extension .rdoc
Example rdoc :README, :layout_engine => :erb

Information technology is not possible to telephone call methods from RDoc, nor to pass locals to it. You therefore will unremarkably use it in combination with some other rendering engine:

                          erb              :overview              ,              :locals              =>              {              :text              =>              rdoc              (              :introduction              )              }                      

Note that y'all may also call the rdoc method from within other templates:

                          %              h1              How-do-you-do              From              Haml              !              %              p              =              rdoc              (              :greetings              )                      

Since y'all cannot call Carmine from RDoc, y'all cannot use layouts written in RDoc. Yet, it is possible to use another rendering engine for the template than for the layout by passing the :layout_engine option.

AsciiDoc Templates

Dependency Asciidoctor
File Extension .asciidoc, .adoc and .advertising
Example asciidoc :README, :layout_engine => :erb

Since you lot cannot telephone call Ruby methods straight from an AsciiDoc template, y'all almost ever want to laissez passer locals to it.

Radius Templates

Dependency Radius
File Extension .radius
Case radius :index, :locals => { :key => 'value' }

Since yous cannot call Ruby methods directly from a Radius template, you almost ever desire to pass locals to it.

Markaby Templates

Dependency Markaby
File Extension .mab
Example markaby { h1 "Welcome!" }

It also takes a block for inline templates (see example).

RABL Templates

Dependency Rabl
File Extension .rabl
Instance rabl :alphabetize

Slim Templates

Dependency Slim Lang
File Extension .slim
Instance slim :alphabetize

Creole Templates

Dependency Creole
File Extension .creole
Example creole :wiki, :layout_engine => :erb

Information technology is not possible to call methods from Creole, nor to pass locals to it. Y'all therefore will usually utilize information technology in combination with another rendering engine:

                          erb              :overview              ,              :locals              =>              {              :text              =>              creole              (              :introduction              )              }                      

Annotation that y'all may too call the creole method from within other templates:

                          %              h1              Hello              From              Haml              !              %              p              =              creole              (              :greetings              )                      

Since yous cannot call Ruby from Creole, you cannot utilize layouts written in Creole. However, information technology is possible to employ another rendering engine for the template than for the layout by passing the :layout_engine option.

MediaWiki Templates

Dependency WikiCloth
File Extension .mediawiki and .mw
Example mediawiki :wiki, :layout_engine => :erb

Information technology is not possible to call methods from MediaWiki markup, nor to pass locals to it. You therefore will usually utilise information technology in combination with another rendering engine:

                          erb              :overview              ,              :locals              =>              {              :text              =>              mediawiki              (              :introduction              )              }                      

Note that y'all may besides call the mediawiki method from inside other templates:

                          %              h1              Hello              From              Haml              !              %              p              =              mediawiki              (              :greetings              )                      

Since you lot cannot call Ruby from MediaWiki, you cannot utilise layouts written in MediaWiki. All the same, it is possible to employ another rendering engine for the template than for the layout by passing the :layout_engine choice.

CoffeeScript Templates

Stylus Templates

Before being able to use Stylus templates, y'all need to load stylus and stylus/tilt commencement:

                          require              'sinatra'              require              'stylus'              require              'stylus/tilt'              go              '/'              do              stylus              :case              terminate                      

Yajl Templates

Dependency yajl-crimson
File Extension .yajl
Instance yajl :index, :locals => { :central => 'qux' }, :callback => 'present', :variable => 'resources'

The template source is evaluated as a Ruby string, and the resulting json variable is converted using #to_json:

                          json              =              {              :foo              =>              'bar'              }              json              [              :baz              ]              =              key                      

The :callback and :variable options can be used to decorate the rendered object:

                          var              resource              =              {              "foo"              :              "bar"              ,              "baz"              :              "qux"              };              present              (              resource              );                      

WLang Templates

Dependency WLang
File Extension .wlang
Instance wlang :index, :locals => { :central => 'value' }

Since calling carmine methods is not idiomatic in WLang, y'all almost always want to laissez passer locals to it. Layouts written in WLang and yield are supported, though.

Accessing Variables in Templates

Templates are evaluated within the same context every bit route handlers. Example variables set in route handlers are directly accessible past templates:

                          go              '/:id'              do              @foo              =              Foo              .              detect              (              params              [              'id'              ])              haml              '%h1= @foo.name'              end                      

Or, specify an explicit Hash of local variables:

                          get              '/:id'              do              foo              =              Foo              .              notice              (              params              [              'id'              ])              haml              '%h1= bar.name'              ,              :locals              =>              {              :bar              =>              foo              }              stop                      

This is typically used when rendering templates every bit partials from within other templates.

Templates with yield and nested layouts

A layout is normally simply a template that calls yield. Such a template can be used either through the :template pick as described above, or information technology tin can exist rendered with a block as follows:

                          erb              :post              ,              :layout              =>              simulated              do              erb              :index              cease                      

This lawmaking is more often than not equivalent to erb :index, :layout => :postal service.

Passing blocks to rendering methods is most useful for creating nested layouts:

                          erb              :main_layout              ,              :layout              =>              false              do              erb              :admin_layout              do              erb              :user              end              end                      

This can also be washed in fewer lines of code with:

                          erb              :admin_layout              ,              :layout              =>              :main_layout              do              erb              :user              end                      

Currently, the following rendering methods accept a block: erb, haml, liquid, slim , wlang. Also the general render method accepts a cake.

Inline Templates

Templates may exist defined at the end of the source file:

                          require              'sinatra'              get              '/'              practice              haml              :alphabetize              end              __END__  @@ layout %html   = yield  @@ index %div.title Hello world.                                    

Annotation: Inline templates defined in the source file that requires sinatra are automatically loaded. Call enable :inline_templates explicitly if yous have inline templates in other source files.

Named Templates

Templates may also be defined using the top-level template method:

                          template              :layout              do              "%html              \n                              =yield              \n              "              cease              template              :index              practise              '%div.title Hello World!'              end              get              '/'              practice              haml              :index              end                      

If a template named "layout" exists, information technology will be used each time a template is rendered. You lot can individually disable layouts by passing :layout => false or disable them by default via set :haml, :layout => false:

                          get              '/'              do              haml              :index              ,              :layout              =>              !              request              .              xhr?              end                      

Associating File Extensions

To acquaintance a file extension with a template engine, use Tilt.register. For instance, if you like to utilize the file extension tt for Textile templates, y'all can do the following:

                          Tilt              .              register              :tt              ,              Tilt              [              :textile              ]                      

Calculation Your Own Template Engine

Commencement, register your engine with Tilt, so create a rendering method:

                          Tilt              .              register              :myat              ,              MyAwesomeTemplateEngine              helpers              do              def              myat              (              *              args              )              render              (              :myat              ,              *              args              )              stop              stop              get              '/'              practise              myat              :index              end                      

Renders ./views/index.myat. Learn more than almost Tilt.

Using Custom Logic for Template Lookup

To implement your own template lookup mechanism yous tin can write your own #find_template method:

                          configure              do              set              :views              ,              [              './views/a'              ,              './views/b'              ]              terminate              def              find_template              (              views              ,              name              ,              engine              ,              &              cake              )              Array              (              views              ).              each              do              |              5              |              super              (              five              ,              proper noun              ,              engine              ,              &              block              )              cease              stop                      

Filters

Before filters are evaluated before each request inside the aforementioned context equally the routes volition be and can alter the asking and response. Example variables fix in filters are accessible by routes and templates:

                          before              practise              @note              =              'Hi!'              asking              .              path_info              =              '/foo/bar/baz'              finish              go              '/foo/*'              do              @note              #=> 'How-do-you-do!'              params              [              'splat'              ]              #=> 'bar/baz'              end                      

After filters are evaluated after each request inside the same context as the routes volition be and tin as well modify the request and response. Example variables set in before filters and routes are attainable by after filters:

                          after              practise              puts              response              .              status              stop                      

Note: Unless y'all use the body method rather than just returning a String from the routes, the body will not yet exist bachelor in the after filter, since it is generated later on.

Filters optionally take a blueprint, causing them to exist evaluated simply if the request path matches that blueprint:

                          earlier              '/protected/*'              do              authenticate!              end              after              '/create/:slug'              do              |              slug              |              session              [              :last_slug              ]              =              slug              end                      

Similar routes, filters also accept conditions:

                          before              :agent              =>              /Songbird/              exercise              # ...              stop              after              '/blog/*'              ,              :host_name              =>              'example.com'              practise              # ...              cease                      

Helpers

Use the top-level helpers method to define helper methods for use in route handlers and templates:

                          helpers              do              def              bar              (              proper name              )              "              #{              name              }              bar"              end              terminate              get              '/:name'              do              bar              (              params              [              'name'              ])              end                      

Alternatively, helper methods can be separately defined in a module:

                          module              FooUtils              def              foo              (              name              )              "              #{              proper name              }              foo"              terminate              end              module              BarUtils              def              bar              (              name              )              "              #{              name              }              bar"              end              cease              helpers              FooUtils              ,              BarUtils                      

The outcome is the same equally including the modules in the application form.

Using Sessions

A session is used to go along state during requests. If activated, you have one session hash per user session:

                          enable              :sessions              become              '/'              do              "value = "              <<              session              [              :value              ].              inspect              terminate              go              '/:value'              do              session              [              'value'              ]              =              params              [              'value'              ]              end                      

Session Hush-hush Security

To meliorate security, the session information in the cookie is signed with a session surreptitious using HMAC-SHA1. This session secret should optimally be a cryptographically secure random value of an appropriate length which for HMAC-SHA1 is greater than or equal to 64 bytes (512 bits, 128 hex characters). Y'all would exist brash not to use a secret that is less than 32 bytes of randomness (256 bits, 64 hex characters). It is therefore very important that you don't only make the hush-hush up, simply instead use a secure random number generator to create information technology. Humans are extremely bad at generating random values.

By default, a 32 byte secure random session secret is generated for y'all past Sinatra, simply it volition change with every restart of your application. If you have multiple instances of your application, and you let Sinatra generate the key, each instance would then take a different session key which is probably not what y'all desire.

For ameliorate security and usability information technology's recommended that y'all generate a secure random secret and store it in an environment variable on each host running your application so that all of your application instances volition share the aforementioned cloak-and-dagger. Yous should periodically rotate this session secret to a new value. Here are some examples of how you might create a 64 byte hush-hush and set up it:

Session Hole-and-corner Generation

            $ scarlet -e "require 'securerandom'; puts SecureRandom.hex(64)" 99ae8af...snip...ec0f262ac                      

Session Hole-and-corner Generation (Bonus Points)

Utilize the sysrandom jewel to prefer use of system RNG facilities to generate random values instead of userspace OpenSSL which MRI Cherry currently defaults to:

            $ jewel install sysrandom Edifice native extensions.  This could accept a while... Successfully installed sysrandom-i.ten ane gem installed  $ ruby -e "require 'sysrandom/securerandom'; puts SecureRandom.hex(64)" 99ae8af...snip...ec0f262ac                      

Session Secret Surroundings Variable

Set a SESSION_SECRET environment variable for Sinatra to the value y'all generated. Make this value persistent across reboots of your host. Since the method for doing this volition vary beyond systems this is for illustrative purposes but:

                          # echo "export SESSION_SECRET=99ae8af...snip...ec0f262ac" >> ~/.bashrc                      

Session Secret App Config

Setup your app config to fail-rubber to a secure random undercover if the SESSION_SECRET environment variable is not bachelor.

For bonus points employ the sysrandom jewel here as well:

                          require              'securerandom'              # -or- require 'sysrandom/securerandom'              prepare              :session_secret              ,              ENV              .              fetch              (              'SESSION_SECRET'              )              {              SecureRandom              .              hex              (              64              )              }                      

Session Config

If yous desire to configure it further, you may also store a hash with options in the sessions setting:

                          ready              :sessions              ,              :domain              =>              'foo.com'                      

To share your session across other apps on subdomains of foo.com, prefix the domain with a . like this instead:

                          set              :sessions              ,              :domain              =>              '.foo.com'                      

Choosing Your Own Session Middleware

Notation that enable :sessions really stores all information in a cookie. This might not ever be what you want (storing lots of data will increase your traffic, for case). You can use any Rack session middleware in guild to do so, one of the following methods can be used:

                          enable              :sessions              set up              :session_store              ,              Rack              ::              Session              ::              Pool                      

Or to set sessions with a hash of options:

                          ready              :sessions              ,              :expire_after              =>              2592000              set up              :session_store              ,              Rack              ::              Session              ::              Pool                      

Another option is to not call enable :sessions, but instead pull in your middleware of choice as you would any other middleware.

It is important to annotation that when using this method, session based protection volition non be enabled by default.

The Rack middleware to do that will also need to be added:

                          apply              Rack              ::              Session              ::              Pool              ,              :expire_after              =>              2592000              utilize              Rack              ::              Protection              ::              RemoteToken              use              Rack              ::              Protection              ::              SessionHijacking                      

See 'Configuring attack protection' for more information.

Halting

To immediately finish a request within a filter or route utilise:

You lot can also specify the condition when halting:

Or the body:

                          halt              'this will be the body'                      

Or both:

With headers:

                          halt              402              ,              {              'Content-Type'              =>              'text/plain'              },              'revenge'                      

It is of course possible to combine a template with halt:

Passing

A route tin punt processing to the next matching road using laissez passer:

                          get              '/judge/:who'              exercise              laissez passer              unless              params              [              'who'              ]              ==              'Frank'              'You got me!'              end              become              '/guess/*'              do              'You missed!'              end                      

The route cake is immediately exited and control continues with the next matching route. If no matching road is found, a 404 is returned.

Triggering Another Road

Sometimes pass is non what y'all want, instead you lot would like to become the result of calling another route. Just apply telephone call to achieve this:

                          get              '/foo'              do              condition              ,              headers              ,              body              =              call              env              .              merge              (              "PATH_INFO"              =>              '/bar'              )              [              status              ,              headers              ,              body              .              map              (              &              :upcase              )]              end              get              '/bar'              do              "bar"              cease                      

Note that in the example in a higher place, you lot would ease testing and increase performance past simply moving "bar" into a helper used by both /foo and /bar.

If you want the request to be sent to the same awarding example rather than a duplicate, use telephone call! instead of call.

Check out the Rack specification if you desire to acquire more about call.

Setting Body, Status Lawmaking and Headers

It is possible and recommended to set the status code and response body with the render value of the route cake. Notwithstanding, in some scenarios y'all might want to set the torso at an arbitrary signal in the execution menstruation. You tin can do so with the body helper method. If y'all do so, you tin use that method from in that location on to access the body:

                          get              '/foo'              practise              trunk              "bar"              end              after              practice              puts              torso              cease                      

It is also possible to laissez passer a block to body, which will be executed by the Rack handler (this can be used to implement streaming, meet "Return Values").

Like to the torso, you tin also set the status code and headers:

                          go              '/foo'              practise              status              418              headers              \              "Allow"              =>              "BREW, Mail service, Get, PROPFIND, WHEN"              ,              "Refresh"              =>              "Refresh: xx; https://ietf.org/rfc/rfc2324.txt"              body              "I'1000 a tea pot!"              end                      

Like body, headers and status with no arguments tin can exist used to access their current values.

Streaming Responses

Sometimes you want to start sending out data while notwithstanding generating parts of the response body. In extreme examples, you desire to proceed sending data until the customer closes the connection. You can use the stream helper to avoid creating your own wrapper:

                          get              '/'              do              stream              practise              |              out              |              out              <<              "It's gonna be legen -              \n              "              sleep              0              .              five              out              <<              " (expect for it)                            \n              "              sleep              one              out              <<              "- dary!              \n              "              end              end                      

This allows you to implement streaming APIs, Server Sent Events, and can be used as the basis for WebSockets. It can also be used to increment throughput if some but not all content depends on a wearisome resources.

Note that the streaming behavior, particularly the number of concurrent requests, highly depends on the spider web server used to serve the application. Some servers might not even support streaming at all. If the server does non support streaming, the body volition be sent all at one time afterward the block passed to stream finishes executing. Streaming does not piece of work at all with Shotgun.

If the optional parameter is gear up to keep_open, it volition non call shut on the stream object, allowing you to close it at any later point in the execution menstruation. This only works on evented servers, like Thin and Rainbows. Other servers will all the same close the stream:

                          # long polling              set              :server              ,              :thin              connections              =              []              go              '/subscribe'              do              # register a client's interest in server events              stream              (              :keep_open              )              do              |              out              |              connections              <<              out              # purge dead connections              connections              .              reject!              (              &              :closed?              )              cease              cease              postal service              '/:message'              do              connections              .              each              do              |              out              |              # notify client that a new bulletin has arrived              out              <<              params              [              'message'              ]              <<              "              \north              "              # bespeak client to connect once more              out              .              close              cease              # acknowledge              "message received"              end                      

It's also possible for the client to shut the connection when trying to write to the socket. Because of this, information technology's recommended to cheque out.closed? before trying to write.

Logging

In the request scope, the logger helper exposes a Logger instance:

                          get              '/'              do              logger              .              info              "loading information"              # ...              cease                      

This logger will automatically accept your Rack handler's logging settings into account. If logging is disabled, this method volition return a dummy object, and then you practise not have to worry about information technology in your routes and filters.

Note that logging is but enabled for Sinatra::Application by default, so if you inherit from Sinatra::Base, you probably want to enable it yourself:

                          grade              MyApp              <              Sinatra              ::              Base              configure              :production              ,              :development              do              enable              :logging              end              end                      

To avoid any logging middleware to be set up, set the logging setting to zilch. However, keep in listen that logger will in that instance render zilch. A common employ case is when y'all want to set up your own logger. Sinatra will use any it will find in env['rack.logger'].

Mime Types

When using send_file or static files you may have mime types Sinatra doesn't understand. Use mime_type to register them by file extension:

                          configure              practice              mime_type              :foo              ,              'text/foo'              stop                      

You tin likewise employ it with the content_type helper:

                          become              '/'              do              content_type              :foo              "foo foo foo"              end                      

Generating URLs

For generating URLs yous should use the url helper method, for case, in Haml:

                          %              a              {              :href              =>              url              (              '/foo'              )}              foo                      

It takes contrary proxies and Rack routers into account, if present.

This method is likewise aliased to to (run into below for an example).

Browser Redirect

You can trigger a browser redirect with the redirect helper method:

                          become              '/foo'              do              redirect              to              (              '/bar'              )              end                      

Whatever additional parameters are handled like arguments passed to halt:

                          redirect              to              (              '/bar'              ),              303              redirect              'http://www.google.com/'              ,              'wrong place, buddy'                      

You can also easily redirect back to the page the user came from with redirect back:

                          get              '/foo'              exercise              "<a href='/bar'>do something</a>"              end              get              '/bar'              exercise              do_something              redirect              back              cease                      

To pass arguments with a redirect, either add them to the query:

                          redirect              to              (              '/bar?sum=42'              )                      

Or use a session:

                          enable              :sessions              get              '/foo'              do              session              [              :clandestine              ]              =              'foo'              redirect              to              (              '/bar'              )              end              get              '/bar'              do              session              [              :cloak-and-dagger              ]              end                      

Cache Control

Setting your headers correctly is the foundation for proper HTTP caching.

You tin can easily set up the Enshroud-Control header like this:

                          get              '/'              do              cache_control              :public              "cache it!"              end                      

Pro tip: Ready caching in a earlier filter:

                          earlier              practise              cache_control              :public              ,              :must_revalidate              ,              :max_age              =>              60              finish                      

If y'all are using the expires helper to gear up the corresponding header, Cache-Control will be set automatically for y'all:

                          before              do              expires              500              ,              :public              ,              :must_revalidate              finish                      

To properly use caches, you should consider using etag or last_modified. It is recommended to call those helpers before doing any heavy lifting, as they will immediately flush a response if the client already has the electric current version in its cache:

                          become              "/commodity/:id"              exercise              @article              =              Commodity              .              notice              params              [              'id'              ]              last_modified              @article              .              updated_at              etag              @article              .              sha1              erb              :article              stop                      

Information technology is also possible to apply a weak ETag:

                          etag              @article              .              sha1              ,              :weak                      

These helpers will not do any caching for you, only rather feed the necessary data to your enshroud. If yous are looking for a quick contrary-proxy caching solution, effort rack-cache:

                          require              "rack/cache"              crave              "sinatra"              use              Rack              ::              Cache              become              '/'              do              cache_control              :public              ,              :max_age              =>              36000              slumber              5              "hello"              end                      

Use the :static_cache_control setting (see below) to add Cache-Control header info to static files.

According to RFC 2616, your application should behave differently if the If-Lucifer or If-None-Match header is set to *, depending on whether the resource requested is already in existence. Sinatra assumes resources for safe (like get) and idempotent (like put) requests are already in existence, whereas other resource (for example post requests) are treated as new resources. You lot can change this behavior by passing in a :new_resource option:

                          get              '/create'              do              etag              ''              ,              :new_resource              =>              truthful              Article              .              create              erb              :new_article              end                      

If you however want to utilise a weak ETag, pass in a :kind option:

                          etag              ''              ,              :new_resource              =>              truthful              ,              :kind              =>              :weak                      

Sending Files

To render the contents of a file equally the response, you lot can use the send_file helper method:

                          get              '/'              do              send_file              'foo.png'              stop                      

It too takes options:

                          send_file              'foo.png'              ,              :type              =>              :jpg                      

The options are:

filename
File name to be used in the response, defaults to the real file name.
last_modified
Value for Final-Modified header, defaults to the file's mtime.
blazon
Value for Content-Blazon header, guessed from the file extension if missing.
disposition
Value for Content-Disposition header, possible values: null (default), :attachment and :inline
length
Value for Content-Length header, defaults to file size.
condition
Status lawmaking to exist sent. Useful when sending a static file as an fault page. If supported by the Rack handler, other ways than streaming from the Cherry-red process will be used. If yous utilise this helper method, Sinatra will automatically handle range requests.

Accessing the Request Object

The incoming asking object can be accessed from request level (filter, routes, fault handlers) through the request method:

                          # app running on http://case.com/example              get              '/foo'              do              t              =              %w[text/css text/html awarding/javascript]              request              .              take              # ['text/html', '*/*']              request              .              accept?              'text/xml'              # true              request              .              preferred_type              (              t              )              # 'text/html'              asking              .              body              # request body sent by the customer (encounter below)              request              .              scheme              # "http"              request              .              script_name              # "/instance"              asking              .              path_info              # "/foo"              asking              .              port              # 80              request              .              request_method              # "Become"              asking              .              query_string              # ""              request              .              content_length              # length of request.body              request              .              media_type              # media blazon of request.body              asking              .              host              # "example.com"              request              .              go?              # true (similar methods for other verbs)              request              .              form_data?              # false              asking              [              "some_param"              ]              # value of some_param parameter. [] is a shortcut to the params hash.              request              .              referrer              # the referrer of the client or '/'              request              .              user_agent              # user amanuensis (used past :amanuensis condition)              asking              .              cookies              # hash of browser cookies              request              .              xhr?              # is this an ajax request?              request              .              url              # "http://example.com/instance/foo"              asking              .              path              # "/instance/foo"              request              .              ip              # client IP address              asking              .              secure?              # false (would be truthful over ssl)              asking              .              forwarded?              # truthful (if running backside a reverse proxy)              request              .              env              # raw env hash handed in by Rack              cease                      

Some options, similar script_name or path_info, tin also exist written:

                          earlier              {              request              .              path_info              =              "/"              }              get              "/"              do              "all requests end up here"              stop                      

The request.body is an IO or StringIO object:

                          post              "/api"              practice              asking              .              body              .              rewind              # in case someone already read it              data              =              JSON              .              parse              request              .              body              .              read              "Howdy                            #{              data              [              'name'              ]              }              !"              end                      

Attachments

You tin use the zipper helper to tell the browser the response should be stored on deejay rather than displayed in the browser:

                          go              '/'              do              attachment              "shop it!"              end                      

You can besides pass it a file proper noun:

                          get              '/'              practise              attachment              "info.txt"              "store it!"              end                      

Dealing with Date and Fourth dimension

Sinatra offers a time_for helper method that generates a Time object from the given value. Information technology is also able to convert DateTime, Appointment and similar classes:

                          get              '/'              practice              laissez passer              if              Time              .              now              >              time_for              (              'Dec 23, 2016'              )              "still time"              terminate                      

This method is used internally past expires, last_modified and akin. You lot tin therefore hands extend the behavior of those methods past overriding time_for in your application:

                          helpers              do              def              time_for              (              value              )              case              value              when              :yesterday              then              Time              .              now              -              24              *              60              *              60              when              :tomorrow              and then              Fourth dimension              .              now              +              24              *              60              *              60              else              super              end              end              stop              go              '/'              practise              last_modified              :yesterday              expires              :tomorrow              "hello"              end                      

Looking Up Template Files

The find_template helper is used to find template files for rendering:

                          find_template              settings              .              views              ,              'foo'              ,              Tilt              [              :haml              ]              practise              |              file              |              puts              "could be                            #{              file              }              "              end                      

This is not really useful. But it is useful that y'all can actually override this method to hook in your ain lookup machinery. For example, if you desire to be able to use more than than ane view directory:

                          gear up              :views              ,              [              'views'              ,              'templates'              ]              helpers              do              def              find_template              (              views              ,              name              ,              engine              ,              &              block              )              Assortment              (              views              ).              each              {              |              v              |              super              (              v              ,              name              ,              engine              ,              &              block              )              }              end              end                      

Another example would be using different directories for different engines:

                          set up              :views              ,              :sass              =>              'views/sass'              ,              :haml              =>              'templates'              ,              :default              =>              'views'              helpers              practice              def              find_template              (              views              ,              proper noun              ,              engine              ,              &              block              )              _              ,              folder              =              views              .              discover              {              |              k              ,              v              |              engine              ==              Tilt              [              chiliad              ]              }              folder              ||=              views              [              :default              ]              super              (              folder              ,              name              ,              engine              ,              &              block              )              terminate              terminate                      

Y'all can likewise hands wrap this upwards in an extension and share with others!

Note that find_template does non cheque if the file really exists just rather calls the given block for all possible paths. This is non a functioning issue, since render will utilise break every bit soon equally a file is establish. Also, template locations (and content) will be cached if you lot are not running in development mode. Yous should keep that in mind if you write a really crazy method.

Configuration

Run once, at startup, in any environment:

                          configure              do              # setting one selection              set              :pick              ,              'value'              # setting multiple options              set              :a              =>              i              ,              :b              =>              2              # same equally `set :option, truthful`              enable              :choice              # same as `set up :selection, false`              disable              :pick              # you can also have dynamic settings with blocks              set              (              :css_dir              )              {              File              .              join              (              views              ,              'css'              )              }              end                      

Run only when the environment (APP_ENV environment variable) is set to :production:

                          configure              :product              exercise              .              .              .              end                      

Run when the environment is set up to either :production or :test:

                          configure              :production              ,              :test              do              .              .              .              finish                      

You tin access those options via settings:

                          configure              practise              prepare              :foo              ,              'bar'              end              get              '/'              practice              settings              .              foo?              # => true              settings              .              foo              # => 'bar'              .              .              .              end                      

Configuring attack protection

Sinatra is using Rack::Protection to defend your application against common, opportunistic attacks. You tin easily disable this beliefs (which will open up up your application to tons of mutual vulnerabilities):

To skip a single defense layer, set protection to an options hash:

                          set              :protection              ,              :except              =>              :path_traversal                      

You can likewise hand in an array in order to disable a listing of protections:

                          set up              :protection              ,              :except              =>              [              :path_traversal              ,              :session_hijacking              ]                      

By default, Sinatra will just set upwards session based protection if :sessions have been enabled. See 'Using Sessions'. Sometimes you may desire to ready up sessions "outside" of the Sinatra app, such as in the config.ru or with a separate Rack::Builder instance. In that instance yous can still set upwards session based protection past passing the :session pick:

                          set              :protection              ,              :session              =>              truthful                      

Bachelor Settings

absolute_redirects
If disabled, Sinatra volition allow relative redirects, notwithstanding, Sinatra will no longer conform with RFC 2616 (HTTP 1.1), which only allows accented redirects.
Enable if your app is running behind a reverse proxy that has not been set up properly. Note that the url helper volition still produce absolute URLs, unless you pass in false as the second parameter.
Disabled by default.
add_charset
Mime types the content_type helper will automatically add the charset info to. Y'all should add to it rather than overriding this option: settings.add_charset << "application/foobar"
app_file
Path to the principal awarding file, used to discover project root, views and public folder and inline templates.
demark
IP accost to bind to (default: 0.0.0.0 or localhost if your `environment` is gear up to development). Only used for built-in server.
default_content_type
Content-Blazon to assume if unknown (defaults to "text/html"). Set to nil to not ready a default Content-Type on every response; when configured and then, yous must fix the Content-Type manually when emitting content or the user-agent will have to sniff information technology (or, if nosniff is enabled in Rack::Protection::XSSHeader, assume application/octet-stream).
default_encoding
Encoding to assume if unknown (defaults to "utf-8").
dump_errors
Display errors in the log.
environment
Current surroundings. Defaults to ENV['APP_ENV'], or "development" if not available.
logging
Apply the logger.
lock
Places a lock around every request, only running processing on asking per Ruby process meantime.
Enabled if your app is not thread-safe. Disabled by default.
method_override
Employ _method magic to allow put/delete forms in browsers that don't back up it.
mustermann_opts
A default hash of options to pass to Mustermann.new when compiling routing paths.
port
Port to listen on. Only used for built-in server.
prefixed_redirects
Whether or not to insert asking.script_name into redirects if no absolute path is given. That manner redirect '/foo' would deport similar redirect to('/foo'). Disabled by default.
protection
Whether or not to enable web attack protections. Run across protection section in a higher place.
public_dir
Alias for public_folder. Come across below.
public_folder
Path to the binder public files are served from. Only used if static file serving is enabled (meet static setting below). Inferred from app_file setting if not set.
quiet
Disables logs generated by Sinatra's kickoff and stop commands. faux by default.
reload_templates
Whether or not to reload templates between requests. Enabled in development manner.
root
Path to project root folder. Inferred from app_file setting if not set.
raise_errors
Heighten exceptions (volition stop application). Enabled by default when environment is set to "test", disabled otherwise.
run
If enabled, Sinatra will handle starting the web server. Do not enable if using rackup or other ways.
running
Is the built-in server running now? Practise not change this setting!
server
Server or list of servers to use for born server. Order indicates priority, default depends on Ruby implementation.
server_settings
If you are using a WEBrick web server, presumably for your development environment, you tin can laissez passer a hash of options to server_settings, such as SSLEnable or SSLVerifyClient. Notwithstanding, web servers such as Puma and Thin practise non support this, so you tin ready server_settings by defining it as a method when you lot phone call configure.
sessions
Enable cookie-based sessions support using Rack::Session::Cookie. See 'Using Sessions' section for more than information.
session_store
The Rack session middleware used. Defaults to Rack::Session::Cookie. Encounter 'Using Sessions' section for more information.
show_exceptions
Testify a stack trace in the browser when an exception happens. Enabled by default when environment is set to "development", disabled otherwise.
Can likewise be set to :after_handler to trigger app-specified fault handling before showing a stack trace in the browser.
static
Whether Sinatra should handle serving static files.
Disable when using a server able to do this on its ain.
Disabling volition boost performance.
Enabled past default in classic style, disabled for modular apps.
static_cache_control
When Sinatra is serving static files, prepare this to add together Cache-Command headers to the responses. Uses the cache_control helper. Disabled by default.
Use an explicit array when setting multiple values: set :static_cache_control, [:public, :max_age => 300]
threaded
If set up to true, will tell Thin to utilise EventMachine.defer for processing the request.
traps
Whether Sinatra should handle system signals.
views
Path to the views binder. Inferred from app_file setting if non fix.
x_cascade
Whether or not to set the 10-Pour header if no route matches. Defaults to true.

Environments

There are three predefined environments: "development", "production" and "examination". Environments tin can be set through the APP_ENV environment variable. The default value is "development". In the "development" environment all templates are reloaded betwixt requests, and special not_found and mistake handlers display stack traces in your browser. In the "production" and "test" environments, templates are cached by default.

To run different environments, set up the APP_ENV surround variable:

                          APP_ENV              =production ruby my_app.rb                      

Y'all can use predefined methods: development?, examination? and production? to cheque the electric current surround setting:

                          get              '/'              practice              if              settings              .              evolution?              "evolution!"              else              "not development!"              end              finish                      

Error Handling

Error handlers run within the same context equally routes and before filters, which means you get all the goodies it has to offer, similar haml, erb, halt, etc.

Not Institute

When a Sinatra::NotFound exception is raised, or the response's status code is 404, the not_found handler is invoked:

                          not_found              do              'This is nowhere to be constitute.'              terminate                      

Error

The mistake handler is invoked any fourth dimension an exception is raised from a route block or a filter. But notation in evolution it will only run if yous set the show exceptions option to :after_handler:

                          gear up              :show_exceptions              ,              :after_handler                      

The exception object can exist obtained from the sinatra.error Rack variable:

                          error              do              'Sorry there was a nasty error - '              +              env              [              'sinatra.error'              ].              message              end                      

Custom errors:

                          error              MyCustomError              exercise              'And so what happened was...'              +              env              [              'sinatra.fault'              ].              bulletin              finish                      

So, if this happens:

                          get              '/'              do              raise              MyCustomError              ,              'something bad'              end                      

You get this:

            So what happened was... something bad                      

Alternatively, you can install an error handler for a condition code:

                          error              403              practise              'Access forbidden'              end              get              '/secret'              practice              403              finish                      

Or a range:

                          error              400              .              .              510              do              'Boom'              end                      

Sinatra installs special not_found and error handlers when running under the evolution environment to brandish nice stack traces and boosted debugging information in your browser.

Rack Middleware

Sinatra rides on Rack, a minimal standard interface for Ruby web frameworks. One of Rack'due south near interesting capabilities for application developers is back up for "middleware" – components that sit down between the server and your application monitoring and/or manipulating the HTTP request/response to provide diverse types of common functionality.

Sinatra makes building Rack middleware pipelines a cinch via a elevation-level use method:

                          require              'sinatra'              crave              'my_custom_middleware'              use              Rack              ::              Lint              utilize              MyCustomMiddleware              go              '/hi'              do              'Hello World'              cease                      

The semantics of use are identical to those defined for the Rack::Architect DSL (most frequently used from rackup files). For example, the use method accepts multiple/variable args as well every bit blocks:

                          use              Rack              ::              Auth              ::              Basic              practise              |              username              ,              password              |              username              ==              'admin'              &&              password              ==              'secret'              stop                      

Rack is distributed with a variety of standard middleware for logging, debugging, URL routing, hallmark, and session handling. Sinatra uses many of these components automatically based on configuration and then you typically don't have to utilize them explicitly.

You can find useful middleware in rack, rack-contrib, or in the Rack wiki.

Testing

Sinatra tests can be written using any Rack-based testing library or framework. Rack::Examination is recommended:

                          require              'my_sinatra_app'              crave              'minitest/autorun'              crave              'rack/test'              class              MyAppTest              <              Minitest              ::              Test              include              Rack              ::              Test              ::              Methods              def              app              Sinatra              ::              Application              end              def              test_my_default              become              '/'              assert_equal              'Hello Earth!'              ,              last_response              .              body              end              def              test_with_params              get              '/run across'              ,              :name              =>              'Frank'              assert_equal              'Hello Frank!'              ,              last_response              .              torso              end              def              test_with_user_agent              get              '/'              ,              {},              'HTTP_USER_AGENT'              =>              'Songbird'              assert_equal              "You're using Songbird!"              ,              last_response              .              body              terminate              terminate                      

Note: If you are using Sinatra in the modular mode, replace Sinatra::Application above with the class name of your app.

Sinatra::Base - Middleware, Libraries, and Modular Apps

Defining your app at the top-level works well for micro-apps just has considerable drawbacks when edifice reusable components such as Rack middleware, Rails metallic, simple libraries with a server component, or even Sinatra extensions. The top-level assumes a micro-app style configuration (due east.yard., a single application file, ./public and ./views directories, logging, exception item page, etc.). That'southward where Sinatra::Base comes into play:

                          crave              'sinatra/base'              class              MyApp              <              Sinatra              ::              Base              set              :sessions              ,              true              prepare              :foo              ,              'bar'              get              '/'              do              'Howdy world!'              stop              end                      

The methods bachelor to Sinatra::Base subclasses are exactly the aforementioned as those available via the top-level DSL. Well-nigh tiptop-level apps tin can be converted to Sinatra::Base components with ii modifications:

  • Your file should crave sinatra/base instead of sinatra; otherwise, all of Sinatra's DSL methods are imported into the chief namespace.
  • Put your app's routes, fault handlers, filters, and options in a subclass of Sinatra::Base.

Sinatra::Base of operations is a blank slate. Most options are disabled past default, including the built-in server. Meet Configuring Settings for details on available options and their behavior. If you want behavior more than similar to when yous ascertain your app at the top level (besides known as Classic mode), you can subclass Sinatra::Application:

                          require              'sinatra/base'              class              MyApp              <              Sinatra              ::              Application              get              '/'              do              'Howdy world!'              terminate              terminate                      

Modular vs. Classic Style

Reverse to common conventionalities, there is cypher wrong with the archetype style. If it suits your awarding, you practise non accept to switch to a modular awarding.

The main disadvantage of using the classic mode rather than the modular style is that y'all will but have one Sinatra application per Ruby process. If y'all plan to apply more than one, switch to the modular way. There is no reason you cannot mix the modular and the classic styles.

If switching from ane style to the other, y'all should exist aware of slightly different default settings:

Setting Classic Modular Modular
app_file file loading sinatra file subclassing Sinatra::Base file subclassing Sinatra::Application
run $0 == app_file simulated false
logging truthful false true
method_override true false true
inline_templates true simulated true
static true File.exist?(public_folder) truthful

Serving a Modular Application

There are ii common options for starting a modular app, actively starting with run!:

                          # my_app.rb              crave              'sinatra/base'              form              MyApp              <              Sinatra              ::              Base              # ... app lawmaking hither ...              # get-go the server if ruby file executed directly              run!              if              app_file              ==              $0              stop                      

Outset with:

Or with a config.ru file, which allows using any Rack handler:

                          # config.ru (run with rackup)              crave              './my_app'              run              MyApp                      

Run:

Using a Classic Style Application with a config.ru

Write your app file:

                          # app.rb              require              'sinatra'              get              '/'              do              'Hi world!'              end                      

And a corresponding config.ru:

                          crave              './app'              run              Sinatra              ::              Application                      

When to use a config.ru?

A config.ru file is recommended if:

  • Yous want to deploy with a different Rack handler (Passenger, Unicorn, Heroku, …).
  • You want to use more than one subclass of Sinatra::Base.
  • Y'all want to apply Sinatra but for middleware, and not as an endpoint.

There is no need to switch to a config.ru simply because you switched to the modular manner, and you don't take to utilise the modular style for running with a config.ru.

Using Sinatra as Middleware

Not just is Sinatra able to employ other Rack middleware, any Sinatra awarding can in plough be added in front of any Rack endpoint every bit middleware itself. This endpoint could be another Sinatra application, or any other Rack-based application (Rails/Hanami/Roda/…):

                          require              'sinatra/base'              class              LoginScreen              <              Sinatra              ::              Base              enable              :sessions              go              (              '/login'              )              {              haml              :login              }              postal service              (              '/login'              )              do              if              params              [              'name'              ]              ==              'admin'              &&              params              [              'password'              ]              ==              'admin'              session              [              'user_name'              ]              =              params              [              'proper name'              ]              else              redirect              '/login'              finish              stop              finish              grade              MyApp              <              Sinatra              ::              Base              # middleware will run before filters              employ              LoginScreen              before              do              unless              session              [              'user_name'              ]              halt              "Admission denied, delight <a href='/login'>login</a>."              cease              cease              become              (              '/'              )              {              "Hello                            #{              session              [              'user_name'              ]              }              ."              }              end                      

Dynamic Application Creation

Sometimes you want to create new applications at runtime without having to assign them to a constant. You lot tin do this with Sinatra.new:

                          require              'sinatra/base'              my_app              =              Sinatra              .              new              {              get              (              '/'              )              {              "hi"              }              }              my_app              .              run!                      

It takes the application to inherit from every bit an optional argument:

                          # config.ru (run with rackup)              require              'sinatra/base of operations'              controller              =              Sinatra              .              new              do              enable              :logging              helpers              MyHelpers              terminate              map              (              '/a'              )              exercise              run              Sinatra              .              new              (              controller              )              {              get              (              '/'              )              {              'a'              }              }              end              map              (              '/b'              )              do              run              Sinatra              .              new              (              controller              )              {              become              (              '/'              )              {              'b'              }              }              end                      

This is particularly useful for testing Sinatra extensions or using Sinatra in your own library.

This also makes using Sinatra as middleware extremely easy:

                          require              'sinatra/base'              use              Sinatra              practice              go              (              '/'              )              {              .              .              .              }              end              run              RailsProject              ::              Application                      

Scopes and Binding

The scope you are currently in determines what methods and variables are available.

Application/Form Telescopic

Every Sinatra awarding corresponds to a subclass of Sinatra::Base. If you are using the summit-level DSL (require 'sinatra'), then this grade is Sinatra::Application, otherwise it is the subclass y'all created explicitly. At class level you have methods like get or before, but y'all cannot access the request or session objects, every bit in that location is only a single application class for all requests.

Options created via ready are methods at grade level:

                          class              MyApp              <              Sinatra              ::              Base              # Hey, I'm in the awarding telescopic!              set              :foo              ,              42              foo              # => 42              get              '/foo'              exercise              # Hey, I'yard no longer in the application scope!              end              stop                      

You have the application scope bounden within:

  • Your application class body
  • Methods defined past extensions
  • The block passed to helpers
  • Procs/blocks used as value for set
  • The cake passed to Sinatra.new

Y'all can reach the scope object (the grade) similar this:

  • Via the object passed to configure blocks (configure { |c| ... })
  • settings from within the request scope

Request/Case Scope

For every incoming request, a new instance of your application class is created, and all handler blocks run in that telescopic. From within this scope y'all can access the request and session objects or call rendering methods like erb or haml. You tin access the application telescopic from within the request scope via the settings helper:

                          class              MyApp              <              Sinatra              ::              Base              # Hey, I'1000 in the awarding scope!              get              '/define_route/:name'              do              # Request telescopic for '/define_route/:name'              @value              =              42              settings              .              become              (              "/              #{              params              [              'proper name'              ]              }              "              )              do              # Asking scope for "/#{params['name']}"              @value              # => nil (not the same request)              end              "Route divers!"              finish              terminate                      

You have the request scope binding within:

  • go, head, post, put, delete, options, patch, link and unlink blocks
  • before and after filters
  • helper methods
  • templates/views

Delegation Scope

The delegation scope merely forwards methods to the class scope. However, it does not behave exactly like the class scope, equally you lot do not accept the class binding. Only methods explicitly marked for delegation are available, and y'all do not share variables/state with the class scope (read: you lot take a different self). You can explicitly add method delegations by calling Sinatra::Delegator.consul :method_name.

Y'all accept the consul scope binding inside:

  • The top level bounden, if you did crave "sinatra"
  • An object extended with the Sinatra::Delegator mixin

Have a wait at the code for yourself: here'southward the Sinatra::Delegator mixin being extending the primary object.

Command Line

Sinatra applications tin be run direct:

            crimson myapp.rb              [-h]              [-10]              [-q]              [-e ENVIRONMENT]              [-p PORT]              [-o HOST]              [-southward HANDLER]                      

Options are:

            -h # assist -p # set the port (default is 4567) -o # set up the host (default is 0.0.0.0) -e # set the environment (default is evolution) -due south # specify rack server/handler (default is sparse) -q # turn on quiet mode for server (default is off) -x # plow on the mutex lock (default is off)                      

Multi-threading

Paraphrasing from this StackOverflow respond by Konstantin

Sinatra doesn't impose any concurrency model, but leaves that to the underlying Rack handler (server) like Thin, Puma or WEBrick. Sinatra itself is thread-condom, so in that location won't be any problem if the Rack handler uses a threaded model of concurrency. This would mean that when starting the server, you'd have to specify the correct invocation method for the specific Rack handler. The following case is a demonstration of how to start a multi-threaded Thin server:

                          # app.rb              require              'sinatra/base'              class              App              <              Sinatra              ::              Base              go              '/'              practise              "How-do-you-do, Globe"              finish              end              App              .              run!                      

To start the server, the control would be:

Requirement

The following Carmine versions are officially supported:

Ruby ii.three
ii.3 is fully supported and recommended. There are currently no plans to drop official support for it.
Rubinius
Rubinius is officially supported (Rubinius >= 2.x). Information technology is recommended to gem install puma.
JRuby
The latest stable release of JRuby is officially supported. It is not recommended to apply C extensions with JRuby. It is recommended to gem install trinidad.

Versions of Ruby prior to two.3 are no longer supported as of Sinatra 2.ane.0.

We as well keep an eye on upcoming Ruby versions.

The following Scarlet implementations are not officially supported but yet are known to run Sinatra:

  • Older versions of JRuby and Rubinius
  • Ruby Enterprise Edition
  • MacRuby, Maglev, IronRuby
  • Ruby 1.9.0 and 1.9.1 (merely we practice recommend confronting using those)

Not being officially supported means if things only break there and not on a supported platform, we assume it'due south not our issue but theirs.

Nosotros also run our CI against ruby-head (hereafter releases of MRI), but we can't guarantee anything, since information technology is constantly moving. Look upcoming 2.x releases to exist fully supported.

Sinatra should work on whatsoever operating system supported by the chosen Cerise implementation.

If you run MacRuby, you should gem install control_tower.

Sinatra currently doesn't run on Key, SmallRuby, BlueRuby or any Ruby version prior to 2.2.

The Bleeding Edge

If y'all would similar to use Sinatra's latest bleeding-border code, experience gratuitous to run your application against the master branch, it should be rather stable.

We as well push button out prerelease gems from time to fourth dimension, so you can do a

            gem install sinatra --pre                      

to get some of the latest features.

With Bundler

If yous want to run your application with the latest Sinatra, using Bundler is the recommended way.

Start, install bundler, if y'all haven't:

And so, in your project directory, create a Gemfile:

                          source              'https://rubygems.org'              gem              'sinatra'              ,              :github              =>              'sinatra/sinatra'              # other dependencies              gem              'haml'              # for instance, if you employ haml                      

Note that you will have to list all your application'due south dependencies in the Gemfile. Sinatra's direct dependencies (Rack and Tilt) volition, even so, be automatically fetched and added by Bundler.

Now y'all tin run your app like this:

            bundle              exec              red myapp.rb                      

Versioning

Basically, Sinatra follows Semantic Versioning, both SemVer and SemVerTag,
but there are some differences. Delight meet as well:

Further Reading

  • Project Website - Boosted documentation, news, and links to other resource.
  • Contributing - Find a problems? Need assistance? Have a patch?
  • Issue tracker
  • Twitter
  • Mailing List
  • IRC: #sinatra on Freenode
  • Sinatra & Friends on Slack (go an invite)
  • Sinatra Book - Cookbook Tutorial
  • Sinatra Recipes - Customs contributed recipes
  • API documentation for the latest release or the electric current Caput on RubyDoc
  • CI server

mortoncappearn91.blogspot.com

Source: http://sinatrarb.com/intro.html

0 Response to "Read From a File in Public Into Sinatra File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel