nano-max-rb 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2952 @@
1
+ # Sinatra
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/sinatra.svg)](https://badge.fury.io/rb/sinatra)
4
+ [![Testing](https://github.com/sinatra/sinatra/actions/workflows/test.yml/badge.svg)](https://github.com/sinatra/sinatra/actions/workflows/test.yml)
5
+
6
+ Sinatra is a [DSL](https://en.wikipedia.org/wiki/Domain-specific_language) for
7
+ quickly creating web applications in Ruby with minimal effort:
8
+
9
+ ```ruby
10
+ # myapp.rb
11
+ require 'sinatra'
12
+
13
+ get '/' do
14
+ 'Hello world!'
15
+ end
16
+ ```
17
+
18
+ Install the gems needed:
19
+
20
+ ```shell
21
+ gem install sinatra rackup puma
22
+ ```
23
+
24
+ And run with:
25
+
26
+ ```shell
27
+ ruby myapp.rb
28
+ ```
29
+
30
+ View at: [http://localhost:4567](http://localhost:4567)
31
+
32
+ The code you changed will not take effect until you restart the server.
33
+ Please restart the server every time you change or use a code reloader
34
+ like [rerun](https://github.com/alexch/rerun) or
35
+ [rack-unreloader](https://github.com/jeremyevans/rack-unreloader).
36
+
37
+ ## Table of Contents
38
+
39
+ - [Sinatra](#sinatra)
40
+ - [Table of Contents](#table-of-contents)
41
+ - [Routes](#routes)
42
+ - [Conditions](#conditions)
43
+ - [Return Values](#return-values)
44
+ - [Custom Route Matchers](#custom-route-matchers)
45
+ - [Static Files](#static-files)
46
+ - [Views / Templates](#views--templates)
47
+ - [Literal Templates](#literal-templates)
48
+ - [Available Template Languages](#available-template-languages)
49
+ - [Haml Templates](#haml-templates)
50
+ - [Erb Templates](#erb-templates)
51
+ - [Builder Templates](#builder-templates)
52
+ - [Nokogiri Templates](#nokogiri-templates)
53
+ - [Sass Templates](#sass-templates)
54
+ - [Scss Templates](#scss-templates)
55
+ - [Liquid Templates](#liquid-templates)
56
+ - [Markdown Templates](#markdown-templates)
57
+ - [RDoc Templates](#rdoc-templates)
58
+ - [AsciiDoc Templates](#asciidoc-templates)
59
+ - [Markaby Templates](#markaby-templates)
60
+ - [RABL Templates](#rabl-templates)
61
+ - [Slim Templates](#slim-templates)
62
+ - [Yajl Templates](#yajl-templates)
63
+ - [Accessing Variables in Templates](#accessing-variables-in-templates)
64
+ - [Templates with `yield` and nested layouts](#templates-with-yield-and-nested-layouts)
65
+ - [Inline Templates](#inline-templates)
66
+ - [Named Templates](#named-templates)
67
+ - [Associating File Extensions](#associating-file-extensions)
68
+ - [Adding Your Own Template Engine](#adding-your-own-template-engine)
69
+ - [Using Custom Logic for Template Lookup](#using-custom-logic-for-template-lookup)
70
+ - [Filters](#filters)
71
+ - [Helpers](#helpers)
72
+ - [Using Sessions](#using-sessions)
73
+ - [Session Secret Security](#session-secret-security)
74
+ - [Session Config](#session-config)
75
+ - [Choosing Your Own Session Middleware](#choosing-your-own-session-middleware)
76
+ - [Halting](#halting)
77
+ - [Passing](#passing)
78
+ - [Triggering Another Route](#triggering-another-route)
79
+ - [Setting Body, Status Code, and Headers](#setting-body-status-code-and-headers)
80
+ - [Streaming Responses](#streaming-responses)
81
+ - [Logging](#logging)
82
+ - [Mime Types](#mime-types)
83
+ - [Generating URLs](#generating-urls)
84
+ - [Browser Redirect](#browser-redirect)
85
+ - [Cache Control](#cache-control)
86
+ - [Sending Files](#sending-files)
87
+ - [Accessing the Request Object](#accessing-the-request-object)
88
+ - [Attachments](#attachments)
89
+ - [Dealing with Date and Time](#dealing-with-date-and-time)
90
+ - [Looking Up Template Files](#looking-up-template-files)
91
+ - [Configuration](#configuration)
92
+ - [Configuring attack protection](#configuring-attack-protection)
93
+ - [Available Settings](#available-settings)
94
+ - [Lifecycle Events](#lifecycle-events)
95
+ - [Environments](#environments)
96
+ - [Error Handling](#error-handling)
97
+ - [Not Found](#not-found)
98
+ - [Error](#error)
99
+ - [Rack Middleware](#rack-middleware)
100
+ - [Testing](#testing)
101
+ - [Sinatra::Base - Middleware, Libraries, and Modular Apps](#sinatrabase---middleware-libraries-and-modular-apps)
102
+ - [Modular vs. Classic Style](#modular-vs-classic-style)
103
+ - [Serving a Modular Application](#serving-a-modular-application)
104
+ - [Using a Classic Style Application with a config.ru](#using-a-classic-style-application-with-a-configru)
105
+ - [When to use a config.ru?](#when-to-use-a-configru)
106
+ - [Using Sinatra as Middleware](#using-sinatra-as-middleware)
107
+ - [Dynamic Application Creation](#dynamic-application-creation)
108
+ - [Scopes and Binding](#scopes-and-binding)
109
+ - [Application/Class Scope](#applicationclass-scope)
110
+ - [Request/Instance Scope](#requestinstance-scope)
111
+ - [Delegation Scope](#delegation-scope)
112
+ - [Command Line](#command-line)
113
+ - [Multi-threading](#multi-threading)
114
+ - [Requirement](#requirement)
115
+ - [The Bleeding Edge](#the-bleeding-edge)
116
+ - [With Bundler](#with-bundler)
117
+ - [Versioning](#versioning)
118
+ - [Further Reading](#further-reading)
119
+
120
+ ## Routes
121
+
122
+ In Sinatra, a route is an HTTP method paired with a URL-matching pattern.
123
+ Each route is associated with a block:
124
+
125
+ ```ruby
126
+ get '/' do
127
+ .. show something ..
128
+ end
129
+
130
+ post '/' do
131
+ .. create something ..
132
+ end
133
+
134
+ put '/' do
135
+ .. replace something ..
136
+ end
137
+
138
+ patch '/' do
139
+ .. modify something ..
140
+ end
141
+
142
+ delete '/' do
143
+ .. annihilate something ..
144
+ end
145
+
146
+ options '/' do
147
+ .. appease something ..
148
+ end
149
+
150
+ link '/' do
151
+ .. affiliate something ..
152
+ end
153
+
154
+ unlink '/' do
155
+ .. separate something ..
156
+ end
157
+ ```
158
+
159
+ Routes are matched in the order they are defined. The first route that
160
+ matches the request is invoked.
161
+
162
+ Routes with trailing slashes are different from the ones without:
163
+
164
+ ```ruby
165
+ get '/foo' do
166
+ # Does not match "GET /foo/"
167
+ end
168
+ ```
169
+
170
+ Route patterns may include named parameters, accessible via the
171
+ `params` hash:
172
+
173
+ ```ruby
174
+ get '/hello/:name' do
175
+ # matches "GET /hello/foo" and "GET /hello/bar"
176
+ # params['name'] is 'foo' or 'bar'
177
+ "Hello #{params['name']}!"
178
+ end
179
+ ```
180
+
181
+ You can also access named parameters via block parameters:
182
+
183
+ ```ruby
184
+ get '/hello/:name' do |n|
185
+ # matches "GET /hello/foo" and "GET /hello/bar"
186
+ # params['name'] is 'foo' or 'bar'
187
+ # n stores params['name']
188
+ "Hello #{n}!"
189
+ end
190
+ ```
191
+
192
+ Route patterns may also include splat (or wildcard) parameters, accessible
193
+ via the `params['splat']` array:
194
+
195
+ ```ruby
196
+ get '/say/*/to/*' do
197
+ # matches /say/hello/to/world
198
+ params['splat'] # => ["hello", "world"]
199
+ end
200
+
201
+ get '/download/*.*' do
202
+ # matches /download/path/to/file.xml
203
+ params['splat'] # => ["path/to/file", "xml"]
204
+ end
205
+ ```
206
+
207
+ Or with block parameters:
208
+
209
+ ```ruby
210
+ get '/download/*.*' do |path, ext|
211
+ [path, ext] # => ["path/to/file", "xml"]
212
+ end
213
+ ```
214
+
215
+ Route matching with Regular Expressions:
216
+
217
+ ```ruby
218
+ get /\/hello\/([\w]+)/ do
219
+ "Hello, #{params['captures'].first}!"
220
+ end
221
+ ```
222
+
223
+ Or with a block parameter:
224
+
225
+ ```ruby
226
+ get %r{/hello/([\w]+)} do |c|
227
+ # Matches "GET /meta/hello/world", "GET /hello/world/1234" etc.
228
+ "Hello, #{c}!"
229
+ end
230
+ ```
231
+
232
+ Route patterns may have optional parameters:
233
+
234
+ ```ruby
235
+ get '/posts/:format?' do
236
+ # matches "GET /posts/" and any extension "GET /posts/json", "GET /posts/xml" etc
237
+ end
238
+ ```
239
+
240
+ Routes may also utilize query parameters:
241
+
242
+ ```ruby
243
+ get '/posts' do
244
+ # matches "GET /posts?title=foo&author=bar"
245
+ title = params['title']
246
+ author = params['author']
247
+ # uses title and author variables; query is optional to the /posts route
248
+ end
249
+ ```
250
+
251
+ By the way, unless you disable the path traversal attack protection (see
252
+ [below](#configuring-attack-protection)), the request path might be modified before
253
+ matching against your routes.
254
+
255
+ You may customize the [Mustermann](https://github.com/sinatra/mustermann#readme)
256
+ options used for a given route by passing in a `:mustermann_opts` hash:
257
+
258
+ ```ruby
259
+ get '\A/posts\z', :mustermann_opts => { :type => :regexp, :check_anchors => false } do
260
+ # matches /posts exactly, with explicit anchoring
261
+ "If you match an anchored pattern clap your hands!"
262
+ end
263
+ ```
264
+
265
+ It looks like a [condition](#conditions), but it isn't one! These options will
266
+ be merged into the global `:mustermann_opts` hash described
267
+ [below](#available-settings).
268
+
269
+ ## Conditions
270
+
271
+ Routes may include a variety of matching conditions, such as the user agent:
272
+
273
+ ```ruby
274
+ get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
275
+ "You're using Songbird version #{params['agent'][0]}"
276
+ end
277
+
278
+ get '/foo' do
279
+ # Matches non-songbird browsers
280
+ end
281
+ ```
282
+
283
+ Other available conditions are `host_name` and `provides`:
284
+
285
+ ```ruby
286
+ get '/', :host_name => /^admin\./ do
287
+ "Admin Area, Access denied!"
288
+ end
289
+
290
+ get '/', :provides => 'html' do
291
+ haml :index
292
+ end
293
+
294
+ get '/', :provides => ['rss', 'atom', 'xml'] do
295
+ builder :feed
296
+ end
297
+ ```
298
+ `provides` searches the request's Accept header.
299
+
300
+ You can easily define your own conditions:
301
+
302
+ ```ruby
303
+ set(:probability) { |value| condition { rand <= value } }
304
+
305
+ get '/win_a_car', :probability => 0.1 do
306
+ "You won!"
307
+ end
308
+
309
+ get '/win_a_car' do
310
+ "Sorry, you lost."
311
+ end
312
+ ```
313
+
314
+ For a condition that takes multiple values use a splat:
315
+
316
+ ```ruby
317
+ set(:auth) do |*roles| # <- notice the splat here
318
+ condition do
319
+ unless logged_in? && roles.any? {|role| current_user.in_role? role }
320
+ redirect "/login/", 303
321
+ end
322
+ end
323
+ end
324
+
325
+ get "/my/account/", :auth => [:user, :admin] do
326
+ "Your Account Details"
327
+ end
328
+
329
+ get "/only/admin/", :auth => :admin do
330
+ "Only admins are allowed here!"
331
+ end
332
+ ```
333
+
334
+ ## Return Values
335
+
336
+ The return value of a route block determines at least the response body
337
+ passed on to the HTTP client or at least the next middleware in the
338
+ Rack stack. Most commonly, this is a string, as in the above examples.
339
+ But other values are also accepted.
340
+
341
+ You can return an object that would either be a valid Rack response, Rack
342
+ body object or HTTP status code:
343
+
344
+ * An Array with three elements: `[status (Integer), headers (Hash), response
345
+ body (responds to #each)]`
346
+ * An Array with two elements: `[status (Integer), response body (responds to
347
+ #each)]`
348
+ * An object that responds to `#each` and passes nothing but strings to
349
+ the given block
350
+ * A Integer representing the status code
351
+
352
+ That way we can, for instance, easily implement a streaming example:
353
+
354
+ ```ruby
355
+ class Stream
356
+ def each
357
+ 100.times { |i| yield "#{i}\n" }
358
+ end
359
+ end
360
+
361
+ get('/') { Stream.new }
362
+ ```
363
+
364
+ You can also use the `stream` helper method ([described below](#streaming-responses)) to reduce
365
+ boilerplate and embed the streaming logic in the route.
366
+
367
+ ## Custom Route Matchers
368
+
369
+ As shown above, Sinatra ships with built-in support for using String
370
+ patterns and regular expressions as route matches. However, it does not
371
+ stop there. You can easily define your own matchers:
372
+
373
+ ```ruby
374
+ class AllButPattern
375
+ def initialize(except)
376
+ @except = except
377
+ end
378
+
379
+ def to_pattern(options)
380
+ return self
381
+ end
382
+
383
+ def params(route)
384
+ return {} unless @except === route
385
+ end
386
+ end
387
+
388
+ def all_but(pattern)
389
+ AllButPattern.new(pattern)
390
+ end
391
+
392
+ get all_but("/index") do
393
+ # ...
394
+ end
395
+ ```
396
+
397
+ Note that the above example might be over-engineered, as it can also be
398
+ expressed as:
399
+
400
+ ```ruby
401
+ get /.*/ do
402
+ pass if request.path_info == "/index"
403
+ # ...
404
+ end
405
+ ```
406
+
407
+ ## Static Files
408
+
409
+ Static files are served from the `./public` directory. You can specify
410
+ a different location by setting the `:public_folder` option:
411
+
412
+ ```ruby
413
+ set :public_folder, __dir__ + '/static'
414
+ ```
415
+
416
+ Note that the public directory name is not included in the URL. A file
417
+ `./public/css/style.css` is made available as
418
+ `http://example.com/css/style.css`.
419
+
420
+ Use the `:static_cache_control` setting (see [below](#cache-control)) to add
421
+ `Cache-Control` header info.
422
+
423
+ By default, Sinatra serves static files from the `public/` folder without running middleware or filters. To add custom headers (e.g, for CORS or caching), use the `:static_headers` setting:
424
+
425
+ ```ruby
426
+ set :static_headers, {
427
+ 'access-control-allow-origin' => '*',
428
+ 'x-static-asset' => 'served-by-sinatra'
429
+ }
430
+ ```
431
+
432
+ ## Views / Templates
433
+
434
+ Each template language is exposed via its own rendering method. These
435
+ methods simply return a string:
436
+
437
+ ```ruby
438
+ get '/' do
439
+ erb :index
440
+ end
441
+ ```
442
+
443
+ This renders `views/index.erb`.
444
+
445
+ Instead of a template name, you can also just pass in the template content
446
+ directly:
447
+
448
+ ```ruby
449
+ get '/' do
450
+ code = "<%= Time.now %>"
451
+ erb code
452
+ end
453
+ ```
454
+
455
+ Templates take a second argument, the options hash:
456
+
457
+ ```ruby
458
+ get '/' do
459
+ erb :index, :layout => :post
460
+ end
461
+ ```
462
+
463
+ This will render `views/index.erb` embedded in the
464
+ `views/post.erb` (default is `views/layout.erb`, if it exists).
465
+
466
+ Any options not understood by Sinatra will be passed on to the template
467
+ engine:
468
+
469
+ ```ruby
470
+ get '/' do
471
+ haml :index, :format => :html5
472
+ end
473
+ ```
474
+
475
+ You can also set options per template language in general:
476
+
477
+ ```ruby
478
+ set :haml, :format => :html5
479
+
480
+ get '/' do
481
+ haml :index
482
+ end
483
+ ```
484
+
485
+ Options passed to the render method override options set via `set`.
486
+
487
+ Available Options:
488
+
489
+ <dl>
490
+ <dt>locals</dt>
491
+ <dd>
492
+ List of locals passed to the document. Handy with partials.
493
+ Example: <tt>erb "<%= foo %>", :locals => {:foo => "bar"}</tt>
494
+ </dd>
495
+
496
+ <dt>default_encoding</dt>
497
+ <dd>
498
+ String encoding to use if uncertain. Defaults to
499
+ <tt>settings.default_encoding</tt>.
500
+ </dd>
501
+
502
+ <dt>views</dt>
503
+ <dd>
504
+ Views folder to load templates from. Defaults to <tt>settings.views</tt>.
505
+ </dd>
506
+
507
+ <dt>layout</dt>
508
+ <dd>
509
+ Whether to use a layout (<tt>true</tt> or <tt>false</tt>). If it's a
510
+ Symbol, specifies what template to use. Example:
511
+ <tt>erb :index, :layout => !request.xhr?</tt>
512
+ </dd>
513
+
514
+ <dt>content_type</dt>
515
+ <dd>
516
+ Content-Type the template produces. Default depends on template language.
517
+ </dd>
518
+
519
+ <dt>scope</dt>
520
+ <dd>
521
+ Scope to render template under. Defaults to the application
522
+ instance. If you change this, instance variables and helper methods
523
+ will not be available.
524
+ </dd>
525
+
526
+ <dt>layout_engine</dt>
527
+ <dd>
528
+ Template engine to use for rendering the layout. Useful for
529
+ languages that do not support layouts otherwise. Defaults to the
530
+ engine used for the template. Example: <tt>set :rdoc, :layout_engine
531
+ => :erb</tt>
532
+ </dd>
533
+
534
+ <dt>layout_options</dt>
535
+ <dd>
536
+ Special options only used for rendering the layout. Example:
537
+ <tt>set :rdoc, :layout_options => { :views => 'views/layouts' }</tt>
538
+ </dd>
539
+ </dl>
540
+
541
+ Templates are assumed to be located directly under the `./views`
542
+ directory. To use a different views directory:
543
+
544
+ ```ruby
545
+ set :views, settings.root + '/templates'
546
+ ```
547
+
548
+
549
+ One important thing to remember is that you always have to reference
550
+ templates with symbols, even if they're in a subdirectory (in this case,
551
+ use: `:'subdir/template'` or `'subdir/template'.to_sym`). You must use a
552
+ symbol because otherwise rendering methods will render any strings
553
+ passed to them directly.
554
+
555
+ ### Literal Templates
556
+
557
+ ```ruby
558
+ get '/' do
559
+ haml '%div.title Hello World'
560
+ end
561
+ ```
562
+
563
+ Renders the template string. You can optionally specify `:path` and
564
+ `:line` for a clearer backtrace if there is a filesystem path or line
565
+ associated with that string:
566
+
567
+ ```ruby
568
+ get '/' do
569
+ haml '%div.title Hello World', :path => 'examples/file.haml', :line => 3
570
+ end
571
+ ```
572
+
573
+ ### Available Template Languages
574
+
575
+ Some languages have multiple implementations. To specify what implementation
576
+ to use (and to be thread-safe), you should simply require it first:
577
+
578
+ ```ruby
579
+ require 'rdiscount'
580
+ get('/') { markdown :index }
581
+ ```
582
+
583
+ #### Haml Templates
584
+
585
+ <table>
586
+ <tr>
587
+ <td>Dependency</td>
588
+ <td><a href="http://haml.info/" title="haml">haml</a></td>
589
+ </tr>
590
+ <tr>
591
+ <td>File Extension</td>
592
+ <td><tt>.haml</tt></td>
593
+ </tr>
594
+ <tr>
595
+ <td>Example</td>
596
+ <td><tt>haml :index, :format => :html5</tt></td>
597
+ </tr>
598
+ </table>
599
+
600
+ #### Erb Templates
601
+
602
+ <table>
603
+ <tr>
604
+ <td>Dependency</td>
605
+ <td>
606
+ <a href="https://github.com/jeremyevans/erubi" title="erubi">erubi</a>
607
+ or erb (included in Ruby)
608
+ </td>
609
+ </tr>
610
+ <tr>
611
+ <td>File Extensions</td>
612
+ <td><tt>.erb</tt>, <tt>.rhtml</tt> or <tt>.erubi</tt> (Erubi only)</td>
613
+ </tr>
614
+ <tr>
615
+ <td>Example</td>
616
+ <td><tt>erb :index</tt></td>
617
+ </tr>
618
+ </table>
619
+
620
+ #### Builder Templates
621
+
622
+ <table>
623
+ <tr>
624
+ <td>Dependency</td>
625
+ <td>
626
+ <a href="https://github.com/jimweirich/builder" title="builder">builder</a>
627
+ </td>
628
+ </tr>
629
+ <tr>
630
+ <td>File Extension</td>
631
+ <td><tt>.builder</tt></td>
632
+ </tr>
633
+ <tr>
634
+ <td>Example</td>
635
+ <td><tt>builder { |xml| xml.em "hi" }</tt></td>
636
+ </tr>
637
+ </table>
638
+
639
+ It also takes a block for inline templates (see [example](#inline-templates)).
640
+
641
+ #### Nokogiri Templates
642
+
643
+ <table>
644
+ <tr>
645
+ <td>Dependency</td>
646
+ <td><a href="http://www.nokogiri.org/" title="nokogiri">nokogiri</a></td>
647
+ </tr>
648
+ <tr>
649
+ <td>File Extension</td>
650
+ <td><tt>.nokogiri</tt></td>
651
+ </tr>
652
+ <tr>
653
+ <td>Example</td>
654
+ <td><tt>nokogiri { |xml| xml.em "hi" }</tt></td>
655
+ </tr>
656
+ </table>
657
+
658
+ It also takes a block for inline templates (see [example](#inline-templates)).
659
+
660
+ #### Sass Templates
661
+
662
+ <table>
663
+ <tr>
664
+ <td>Dependency</td>
665
+ <td><a href="https://github.com/ntkme/sass-embedded-host-ruby" title="sass-embedded">sass-embedded</a></td>
666
+ </tr>
667
+ <tr>
668
+ <td>File Extension</td>
669
+ <td><tt>.sass</tt></td>
670
+ </tr>
671
+ <tr>
672
+ <td>Example</td>
673
+ <td><tt>sass :stylesheet, :style => :expanded</tt></td>
674
+ </tr>
675
+ </table>
676
+
677
+ #### Scss Templates
678
+
679
+ <table>
680
+ <tr>
681
+ <td>Dependency</td>
682
+ <td><a href="https://github.com/ntkme/sass-embedded-host-ruby" title="sass-embedded">sass-embedded</a></td>
683
+ </tr>
684
+ <tr>
685
+ <td>File Extension</td>
686
+ <td><tt>.scss</tt></td>
687
+ </tr>
688
+ <tr>
689
+ <td>Example</td>
690
+ <td><tt>scss :stylesheet, :style => :expanded</tt></td>
691
+ </tr>
692
+ </table>
693
+
694
+ #### Liquid Templates
695
+
696
+ <table>
697
+ <tr>
698
+ <td>Dependency</td>
699
+ <td><a href="https://shopify.github.io/liquid/" title="liquid">liquid</a></td>
700
+ </tr>
701
+ <tr>
702
+ <td>File Extension</td>
703
+ <td><tt>.liquid</tt></td>
704
+ </tr>
705
+ <tr>
706
+ <td>Example</td>
707
+ <td><tt>liquid :index, :locals => { :key => 'value' }</tt></td>
708
+ </tr>
709
+ </table>
710
+
711
+ Since you cannot call Ruby methods (except for `yield`) from a Liquid
712
+ template, you almost always want to pass locals to it.
713
+
714
+ #### Markdown Templates
715
+
716
+ <table>
717
+ <tr>
718
+ <td>Dependency</td>
719
+ <td>
720
+ Anyone of:
721
+ <a href="https://github.com/davidfstr/rdiscount" title="RDiscount">RDiscount</a>,
722
+ <a href="https://github.com/vmg/redcarpet" title="RedCarpet">RedCarpet</a>,
723
+ <a href="https://kramdown.gettalong.org/" title="kramdown">kramdown</a>,
724
+ <a href="https://github.com/gjtorikian/commonmarker" title="commonmarker">commonmarker</a>
725
+ <a href="https://github.com/alphabetum/pandoc-ruby" title="pandoc">pandoc</a>
726
+ </td>
727
+ </tr>
728
+ <tr>
729
+ <td>File Extensions</td>
730
+ <td><tt>.markdown</tt>, <tt>.mkd</tt> and <tt>.md</tt></td>
731
+ </tr>
732
+ <tr>
733
+ <td>Example</td>
734
+ <td><tt>markdown :index, :layout_engine => :erb</tt></td>
735
+ </tr>
736
+ </table>
737
+
738
+ It is not possible to call methods from Markdown, nor to pass locals to it.
739
+ You therefore will usually use it in combination with another rendering
740
+ engine:
741
+
742
+ ```ruby
743
+ erb :overview, :locals => { :text => markdown(:introduction) }
744
+ ```
745
+
746
+ Note that you may also call the `markdown` method from within other
747
+ templates:
748
+
749
+ ```ruby
750
+ %h1 Hello From Haml!
751
+ %p= markdown(:greetings)
752
+ ```
753
+
754
+ Since you cannot call Ruby from Markdown, you cannot use layouts written in
755
+ Markdown. However, it is possible to use another rendering engine for the
756
+ template than for the layout by passing the `:layout_engine` option.
757
+
758
+ #### RDoc Templates
759
+
760
+ <table>
761
+ <tr>
762
+ <td>Dependency</td>
763
+ <td><a href="http://rdoc.sourceforge.net/" title="RDoc">RDoc</a></td>
764
+ </tr>
765
+ <tr>
766
+ <td>File Extension</td>
767
+ <td><tt>.rdoc</tt></td>
768
+ </tr>
769
+ <tr>
770
+ <td>Example</td>
771
+ <td><tt>rdoc :README, :layout_engine => :erb</tt></td>
772
+ </tr>
773
+ </table>
774
+
775
+ It is not possible to call methods from RDoc, nor to pass locals to it. You
776
+ therefore will usually use it in combination with another rendering engine:
777
+
778
+ ```ruby
779
+ erb :overview, :locals => { :text => rdoc(:introduction) }
780
+ ```
781
+
782
+ Note that you may also call the `rdoc` method from within other templates:
783
+
784
+ ```ruby
785
+ %h1 Hello From Haml!
786
+ %p= rdoc(:greetings)
787
+ ```
788
+
789
+ Since you cannot call Ruby from RDoc, you cannot use layouts written in
790
+ RDoc. However, it is possible to use another rendering engine for the
791
+ template than for the layout by passing the `:layout_engine` option.
792
+
793
+ #### AsciiDoc Templates
794
+
795
+ <table>
796
+ <tr>
797
+ <td>Dependency</td>
798
+ <td><a href="http://asciidoctor.org/" title="Asciidoctor">Asciidoctor</a></td>
799
+ </tr>
800
+ <tr>
801
+ <td>File Extension</td>
802
+ <td><tt>.asciidoc</tt>, <tt>.adoc</tt> and <tt>.ad</tt></td>
803
+ </tr>
804
+ <tr>
805
+ <td>Example</td>
806
+ <td><tt>asciidoc :README, :layout_engine => :erb</tt></td>
807
+ </tr>
808
+ </table>
809
+
810
+ Since you cannot call Ruby methods directly from an AsciiDoc template, you
811
+ almost always want to pass locals to it.
812
+
813
+ #### Markaby Templates
814
+
815
+ <table>
816
+ <tr>
817
+ <td>Dependency</td>
818
+ <td><a href="https://markaby.github.io/" title="Markaby">Markaby</a></td>
819
+ </tr>
820
+ <tr>
821
+ <td>File Extension</td>
822
+ <td><tt>.mab</tt></td>
823
+ </tr>
824
+ <tr>
825
+ <td>Example</td>
826
+ <td><tt>markaby { h1 "Welcome!" }</tt></td>
827
+ </tr>
828
+ </table>
829
+
830
+ It also takes a block for inline templates (see [example](#inline-templates)).
831
+
832
+ #### RABL Templates
833
+
834
+ <table>
835
+ <tr>
836
+ <td>Dependency</td>
837
+ <td><a href="https://github.com/nesquena/rabl" title="Rabl">Rabl</a></td>
838
+ </tr>
839
+ <tr>
840
+ <td>File Extension</td>
841
+ <td><tt>.rabl</tt></td>
842
+ </tr>
843
+ <tr>
844
+ <td>Example</td>
845
+ <td><tt>rabl :index</tt></td>
846
+ </tr>
847
+ </table>
848
+
849
+ #### Slim Templates
850
+
851
+ <table>
852
+ <tr>
853
+ <td>Dependency</td>
854
+ <td><a href="https://slim-template.github.io/" title="Slim Lang">Slim Lang</a></td>
855
+ </tr>
856
+ <tr>
857
+ <td>File Extension</td>
858
+ <td><tt>.slim</tt></td>
859
+ </tr>
860
+ <tr>
861
+ <td>Example</td>
862
+ <td><tt>slim :index</tt></td>
863
+ </tr>
864
+ </table>
865
+
866
+ #### Yajl Templates
867
+
868
+ <table>
869
+ <tr>
870
+ <td>Dependency</td>
871
+ <td><a href="https://github.com/brianmario/yajl-ruby" title="yajl-ruby">yajl-ruby</a></td>
872
+ </tr>
873
+ <tr>
874
+ <td>File Extension</td>
875
+ <td><tt>.yajl</tt></td>
876
+ </tr>
877
+ <tr>
878
+ <td>Example</td>
879
+ <td>
880
+ <tt>
881
+ yajl :index,
882
+ :locals => { :key => 'qux' },
883
+ :callback => 'present',
884
+ :variable => 'resource'
885
+ </tt>
886
+ </td>
887
+ </tr>
888
+ </table>
889
+
890
+
891
+ The template source is evaluated as a Ruby string, and the
892
+ resulting json variable is converted using `#to_json`:
893
+
894
+ ```ruby
895
+ json = { :foo => 'bar' }
896
+ json[:baz] = key
897
+ ```
898
+
899
+ The `:callback` and `:variable` options can be used to decorate the rendered
900
+ object:
901
+
902
+ ```javascript
903
+ var resource = {"foo":"bar","baz":"qux"};
904
+ present(resource);
905
+ ```
906
+
907
+ ### Accessing Variables in Templates
908
+
909
+ Templates are evaluated within the same context as route handlers. Instance
910
+ variables set in route handlers are directly accessible by templates:
911
+
912
+ ```ruby
913
+ get '/:id' do
914
+ @foo = Foo.find(params['id'])
915
+ haml '%h1= @foo.name'
916
+ end
917
+ ```
918
+
919
+ Or, specify an explicit Hash of local variables:
920
+
921
+ ```ruby
922
+ get '/:id' do
923
+ foo = Foo.find(params['id'])
924
+ haml '%h1= bar.name', :locals => { :bar => foo }
925
+ end
926
+ ```
927
+
928
+ This is typically used when rendering templates as partials from within
929
+ other templates.
930
+
931
+ ### Templates with `yield` and nested layouts
932
+
933
+ A layout is usually just a template that calls `yield`.
934
+ Such a template can be used either through the `:template` option as
935
+ described above, or it can be rendered with a block as follows:
936
+
937
+ ```ruby
938
+ erb :post, :layout => false do
939
+ erb :index
940
+ end
941
+ ```
942
+
943
+ This code is mostly equivalent to `erb :index, :layout => :post`.
944
+
945
+ Passing blocks to rendering methods is most useful for creating nested
946
+ layouts:
947
+
948
+ ```ruby
949
+ erb :main_layout, :layout => false do
950
+ erb :admin_layout do
951
+ erb :user
952
+ end
953
+ end
954
+ ```
955
+
956
+ This can also be done in fewer lines of code with:
957
+
958
+ ```ruby
959
+ erb :admin_layout, :layout => :main_layout do
960
+ erb :user
961
+ end
962
+ ```
963
+
964
+ Currently, the following rendering methods accept a block: `erb`, `haml`,
965
+ `liquid`, `slim `. Also, the general `render` method accepts a block.
966
+
967
+ ### Inline Templates
968
+
969
+ Templates may be defined at the end of the source file:
970
+
971
+ ```ruby
972
+ require 'sinatra'
973
+
974
+ get '/' do
975
+ haml :index
976
+ end
977
+
978
+ __END__
979
+
980
+ @@ layout
981
+ %html
982
+ != yield
983
+
984
+ @@ index
985
+ %div.title Hello world.
986
+ ```
987
+
988
+ NOTE: Inline templates defined in the source file that requires Sinatra are
989
+ automatically loaded. Call `enable :inline_templates` explicitly if you
990
+ have inline templates in other source files.
991
+
992
+ ### Named Templates
993
+
994
+ Templates may also be defined using the top-level `template` method:
995
+
996
+ ```ruby
997
+ template :layout do
998
+ "%html\n =yield\n"
999
+ end
1000
+
1001
+ template :index do
1002
+ '%div.title Hello World!'
1003
+ end
1004
+
1005
+ get '/' do
1006
+ haml :index
1007
+ end
1008
+ ```
1009
+
1010
+ If a template named "layout" exists, it will be used each time a template
1011
+ is rendered. You can individually disable layouts by passing
1012
+ `:layout => false` or disable them by default via
1013
+ `set :haml, :layout => false`:
1014
+
1015
+ ```ruby
1016
+ get '/' do
1017
+ haml :index, :layout => !request.xhr?
1018
+ end
1019
+ ```
1020
+
1021
+ ### Associating File Extensions
1022
+
1023
+ To associate a file extension with a template engine, use
1024
+ `Tilt.register`. For instance, if you like to use the file extension
1025
+ `tt` for Haml templates, you can do the following:
1026
+
1027
+ ```ruby
1028
+ Tilt.register Tilt[:haml], :tt
1029
+ ```
1030
+
1031
+ ### Adding Your Own Template Engine
1032
+
1033
+ First, register your engine with Tilt, then create a rendering method:
1034
+
1035
+ ```ruby
1036
+ Tilt.register MyAwesomeTemplateEngine, :myat
1037
+
1038
+ helpers do
1039
+ def myat(*args) render(:myat, *args) end
1040
+ end
1041
+
1042
+ get '/' do
1043
+ myat :index
1044
+ end
1045
+ ```
1046
+
1047
+ Renders `./views/index.myat`. Learn more about
1048
+ [Tilt](https://github.com/rtomayko/tilt#readme).
1049
+
1050
+ ### Using Custom Logic for Template Lookup
1051
+
1052
+ To implement your own template lookup mechanism you can write your
1053
+ own `#find_template` method:
1054
+
1055
+ ```ruby
1056
+ configure do
1057
+ set :views, [ './views/a', './views/b' ]
1058
+ end
1059
+
1060
+ def find_template(views, name, engine, &block)
1061
+ Array(views).each do |v|
1062
+ super(v, name, engine, &block)
1063
+ end
1064
+ end
1065
+ ```
1066
+
1067
+ ## Filters
1068
+
1069
+ Before filters are evaluated before each request within the same context
1070
+ as the routes will be and can modify the request and response. Instance
1071
+ variables set in filters are accessible by routes and templates:
1072
+
1073
+ ```ruby
1074
+ before do
1075
+ @note = 'Hi!'
1076
+ request.path_info = '/foo/bar/baz'
1077
+ end
1078
+
1079
+ get '/foo/*' do
1080
+ @note #=> 'Hi!'
1081
+ params['splat'] #=> 'bar/baz'
1082
+ end
1083
+ ```
1084
+
1085
+ After filters are evaluated after each request within the same context
1086
+ as the routes will be and can also modify the request and response.
1087
+ Instance variables set in before filters and routes are accessible by
1088
+ after filters:
1089
+
1090
+ ```ruby
1091
+ after do
1092
+ puts response.status
1093
+ end
1094
+ ```
1095
+
1096
+ Note: Unless you use the `body` method rather than just returning a
1097
+ String from the routes, the body will not yet be available in the after
1098
+ filter, since it is generated later on.
1099
+
1100
+ Filters optionally take a pattern, causing them to be evaluated only if the
1101
+ request path matches that pattern:
1102
+
1103
+ ```ruby
1104
+ before '/protected/*' do
1105
+ authenticate!
1106
+ end
1107
+
1108
+ after '/create/:slug' do |slug|
1109
+ session[:last_slug] = slug
1110
+ end
1111
+ ```
1112
+
1113
+ Like routes, filters also take conditions:
1114
+
1115
+ ```ruby
1116
+ before :agent => /Songbird/ do
1117
+ # ...
1118
+ end
1119
+
1120
+ after '/blog/*', :host_name => 'example.com' do
1121
+ # ...
1122
+ end
1123
+ ```
1124
+
1125
+ ## Helpers
1126
+
1127
+ Use the top-level `helpers` method to define helper methods for use in
1128
+ route handlers and templates:
1129
+
1130
+ ```ruby
1131
+ helpers do
1132
+ def bar(name)
1133
+ "#{name}bar"
1134
+ end
1135
+ end
1136
+
1137
+ get '/:name' do
1138
+ bar(params['name'])
1139
+ end
1140
+ ```
1141
+
1142
+ Alternatively, helper methods can be separately defined in a module:
1143
+
1144
+ ```ruby
1145
+ module FooUtils
1146
+ def foo(name) "#{name}foo" end
1147
+ end
1148
+
1149
+ module BarUtils
1150
+ def bar(name) "#{name}bar" end
1151
+ end
1152
+
1153
+ helpers FooUtils, BarUtils
1154
+ ```
1155
+
1156
+ The effect is the same as including the modules in the application class.
1157
+
1158
+ ### Using Sessions
1159
+
1160
+ A session is used to keep state during requests. If activated, you have one
1161
+ session hash per user session:
1162
+
1163
+ ```ruby
1164
+ enable :sessions
1165
+
1166
+ get '/' do
1167
+ "value = " << session[:value].inspect
1168
+ end
1169
+
1170
+ get '/:value' do
1171
+ session['value'] = params['value']
1172
+ end
1173
+ ```
1174
+
1175
+ #### Session Secret Security
1176
+
1177
+ To improve security, the session data in the cookie is signed with a session
1178
+ secret using `HMAC-SHA1`. This session secret should optimally be a
1179
+ cryptographically secure random value of an appropriate length which for
1180
+ `HMAC-SHA1` is greater than or equal to 64 bytes (512 bits, 128 hex
1181
+ characters). You would be advised not to use a secret that is less than 32
1182
+ bytes of randomness (256 bits, 64 hex characters). It is therefore **very
1183
+ important** that you don't just make the secret up, but instead use a secure
1184
+ random number generator to create it. Humans are extremely bad at generating
1185
+ random values.
1186
+
1187
+ By default, a 32 byte secure random session secret is generated for you by
1188
+ Sinatra, but it will change with every restart of your application. If you
1189
+ have multiple instances of your application, and you let Sinatra generate the
1190
+ key, each instance would then have a different session key which is probably
1191
+ not what you want.
1192
+
1193
+ For better security and usability it's
1194
+ [recommended](https://12factor.net/config) that you generate a secure random
1195
+ secret and store it in an environment variable on each host running your
1196
+ application so that all of your application instances will share the same
1197
+ secret. You should periodically rotate this session secret to a new value.
1198
+ Here are some examples of how you might create a 64-byte secret and set it:
1199
+
1200
+ **Session Secret Generation**
1201
+
1202
+ ```text
1203
+ $ ruby -e "require 'securerandom'; puts SecureRandom.hex(64)"
1204
+ 99ae8af...snip...ec0f262ac
1205
+ ```
1206
+
1207
+ **Session Secret Environment Variable**
1208
+
1209
+ Set a `SESSION_SECRET` environment variable for Sinatra to the value you
1210
+ generated. Make this value persistent across reboots of your host. Since the
1211
+ method for doing this will vary across systems this is for illustrative
1212
+ purposes only:
1213
+
1214
+ ```bash
1215
+ # echo "export SESSION_SECRET=99ae8af...snip...ec0f262ac" >> ~/.bashrc
1216
+ ```
1217
+
1218
+ **Session Secret App Config**
1219
+
1220
+ Set up your app config to fail-safe to a secure random secret
1221
+ if the `SESSION_SECRET` environment variable is not available:
1222
+
1223
+ ```ruby
1224
+ require 'securerandom'
1225
+ set :session_secret, ENV.fetch('SESSION_SECRET') { SecureRandom.hex(64) }
1226
+ ```
1227
+
1228
+ #### Session Config
1229
+
1230
+ If you want to configure it further, you may also store a hash with options
1231
+ in the `sessions` setting:
1232
+
1233
+ ```ruby
1234
+ set :sessions, :domain => 'foo.com'
1235
+ ```
1236
+
1237
+ To share your session across other apps on subdomains of foo.com, prefix the
1238
+ domain with a *.* like this instead:
1239
+
1240
+ ```ruby
1241
+ set :sessions, :domain => '.foo.com'
1242
+ ```
1243
+
1244
+ #### Choosing Your Own Session Middleware
1245
+
1246
+ Note that `enable :sessions` actually stores all data in a cookie. This
1247
+ might not always be what you want (storing lots of data will increase your
1248
+ traffic, for instance). You can use any Rack session middleware in order to
1249
+ do so, one of the following methods can be used:
1250
+
1251
+ ```ruby
1252
+ enable :sessions
1253
+ set :session_store, Rack::Session::Pool
1254
+ ```
1255
+
1256
+ Or to set up sessions with a hash of options:
1257
+
1258
+ ```ruby
1259
+ set :sessions, :expire_after => 2592000
1260
+ set :session_store, Rack::Session::Pool
1261
+ ```
1262
+
1263
+ Another option is to **not** call `enable :sessions`, but instead pull in
1264
+ your middleware of choice as you would any other middleware.
1265
+
1266
+ It is important to note that when using this method, session based
1267
+ protection **will not be enabled by default**.
1268
+
1269
+ The Rack middleware to do that will also need to be added:
1270
+
1271
+ ```ruby
1272
+ use Rack::Session::Pool, :expire_after => 2592000
1273
+ use Rack::Protection::RemoteToken
1274
+ use Rack::Protection::SessionHijacking
1275
+ ```
1276
+
1277
+ See '[Configuring attack protection](#configuring-attack-protection)' for more information.
1278
+
1279
+ ### Halting
1280
+
1281
+ To immediately stop a request within a filter or route use:
1282
+
1283
+ ```ruby
1284
+ halt
1285
+ ```
1286
+
1287
+ You can also specify the status when halting:
1288
+
1289
+ ```ruby
1290
+ halt 410
1291
+ ```
1292
+
1293
+ Or the body:
1294
+
1295
+ ```ruby
1296
+ halt 'this will be the body'
1297
+ ```
1298
+
1299
+ Or both:
1300
+
1301
+ ```ruby
1302
+ halt 401, 'go away!'
1303
+ ```
1304
+
1305
+ With headers:
1306
+
1307
+ ```ruby
1308
+ halt 402, {'Content-Type' => 'text/plain'}, 'revenge'
1309
+ ```
1310
+
1311
+ It is of course possible to combine a template with `halt`:
1312
+
1313
+ ```ruby
1314
+ halt erb(:error)
1315
+ ```
1316
+
1317
+ ### Passing
1318
+
1319
+ A route can punt processing to the next matching route using `pass`:
1320
+
1321
+ ```ruby
1322
+ get '/guess/:who' do
1323
+ pass unless params['who'] == 'Frank'
1324
+ 'You got me!'
1325
+ end
1326
+
1327
+ get '/guess/*' do
1328
+ 'You missed!'
1329
+ end
1330
+ ```
1331
+
1332
+ The route block is immediately exited and control continues with the next
1333
+ matching route. If no matching route is found, a 404 is returned.
1334
+
1335
+ ### Triggering Another Route
1336
+
1337
+ Sometimes `pass` is not what you want, instead, you would like to get the
1338
+ result of calling another route. Simply use `call` to achieve this:
1339
+
1340
+ ```ruby
1341
+ get '/foo' do
1342
+ status, headers, body = call env.merge("PATH_INFO" => '/bar')
1343
+ [status, headers, body.map(&:upcase)]
1344
+ end
1345
+
1346
+ get '/bar' do
1347
+ "bar"
1348
+ end
1349
+ ```
1350
+
1351
+ Note that in the example above, you would ease testing and increase
1352
+ performance by simply moving `"bar"` into a helper used by both `/foo` and
1353
+ `/bar`.
1354
+
1355
+ If you want the request to be sent to the same application instance rather
1356
+ than a duplicate, use `call!` instead of `call`.
1357
+
1358
+ Check out the Rack specification if you want to learn more about `call`.
1359
+
1360
+ ### Setting Body, Status Code, and Headers
1361
+
1362
+ It is possible and recommended to set the status code and response body with
1363
+ the return value of the route block. However, in some scenarios, you might
1364
+ want to set the body at an arbitrary point in the execution flow. You can do
1365
+ so with the `body` helper method. If you do so, you can use that method from
1366
+ thereon to access the body:
1367
+
1368
+ ```ruby
1369
+ get '/foo' do
1370
+ body "bar"
1371
+ end
1372
+
1373
+ after do
1374
+ puts body
1375
+ end
1376
+ ```
1377
+
1378
+ It is also possible to pass a block to `body`, which will be executed by the
1379
+ Rack handler (this can be used to implement streaming, [see "Return Values"](#return-values)).
1380
+
1381
+ Similar to the body, you can also set the status code and headers:
1382
+
1383
+ ```ruby
1384
+ get '/foo' do
1385
+ status 418
1386
+ headers \
1387
+ "Allow" => "BREW, POST, GET, PROPFIND, WHEN",
1388
+ "Refresh" => "Refresh: 20; https://ietf.org/rfc/rfc2324.txt"
1389
+ body "I'm a teapot!"
1390
+ end
1391
+ ```
1392
+
1393
+ Like `body`, `headers` and `status` with no arguments can be used to access
1394
+ their current values.
1395
+
1396
+ ### Streaming Responses
1397
+
1398
+ Sometimes you want to start sending out data while still generating parts of
1399
+ the response body. In extreme examples, you want to keep sending data until
1400
+ the client closes the connection. You can use the `stream` helper to avoid
1401
+ creating your own wrapper:
1402
+
1403
+ ```ruby
1404
+ get '/' do
1405
+ stream do |out|
1406
+ out << "It's gonna be legen -\n"
1407
+ sleep 0.5
1408
+ out << " (wait for it) \n"
1409
+ sleep 1
1410
+ out << "- dary!\n"
1411
+ end
1412
+ end
1413
+ ```
1414
+
1415
+ This allows you to implement streaming APIs,
1416
+ [Server Sent Events](https://w3c.github.io/eventsource/), and can be used as
1417
+ the basis for [WebSockets](https://en.wikipedia.org/wiki/WebSocket). It can
1418
+ also be used to increase throughput if some but not all content depends on a
1419
+ slow resource.
1420
+
1421
+ Note that the streaming behavior, especially the number of concurrent
1422
+ requests, highly depends on the webserver used to serve the application.
1423
+ Some servers might not even support streaming at all. If the server does not
1424
+ support streaming, the body will be sent all at once after the block passed
1425
+ to `stream` finishes executing. Streaming does not work at all with Shotgun.
1426
+
1427
+ If the optional parameter is set to `keep_open`, it will not call `close` on
1428
+ the stream object, allowing you to close it at any later point in the
1429
+ execution flow.
1430
+
1431
+ You can have a look at the [chat example](https://github.com/sinatra/sinatra/blob/main/examples/chat.rb)
1432
+
1433
+ It's also possible for the client to close the connection when trying to
1434
+ write to the socket. Because of this, it's recommended to check
1435
+ `out.closed?` before trying to write.
1436
+
1437
+ ### Logging
1438
+
1439
+ In the request scope, the `logger` helper exposes a `Logger` instance:
1440
+
1441
+ ```ruby
1442
+ get '/' do
1443
+ logger.info "loading data"
1444
+ # ...
1445
+ end
1446
+ ```
1447
+
1448
+ This logger will automatically take your Rack handler's logging settings into
1449
+ account. If logging is disabled, this method will return a dummy object, so
1450
+ you do not have to worry about it in your routes and filters.
1451
+
1452
+ Note that logging is only enabled for `Sinatra::Application` by default, so
1453
+ if you inherit from `Sinatra::Base`, you probably want to enable it yourself:
1454
+
1455
+ ```ruby
1456
+ class MyApp < Sinatra::Base
1457
+ configure :production, :development do
1458
+ enable :logging
1459
+ end
1460
+ end
1461
+ ```
1462
+
1463
+ To avoid any logging middleware to be set up, set the `logging` option to
1464
+ `nil`. However, keep in mind that `logger` will in that case return `nil`. A
1465
+ common use case is when you want to set your own logger. Sinatra will use
1466
+ whatever it will find in `env['rack.logger']`.
1467
+
1468
+ ### Mime Types
1469
+
1470
+ When using `send_file` or static files you may have mime types Sinatra
1471
+ doesn't understand. Use `mime_type` to register them by file extension:
1472
+
1473
+ ```ruby
1474
+ configure do
1475
+ mime_type :foo, 'text/foo'
1476
+ end
1477
+ ```
1478
+
1479
+ You can also use it with the `content_type` helper:
1480
+
1481
+ ```ruby
1482
+ get '/' do
1483
+ content_type :foo
1484
+ "foo foo foo"
1485
+ end
1486
+ ```
1487
+
1488
+ ### Generating URLs
1489
+
1490
+ For generating URLs you should use the `url` helper method, for instance, in
1491
+ Haml:
1492
+
1493
+ ```ruby
1494
+ %a{:href => url('/foo')} foo
1495
+ ```
1496
+
1497
+ It takes reverse proxies and Rack routers into account - if present.
1498
+
1499
+ This method is also aliased to `to` (see [below](#browser-redirect) for an example).
1500
+
1501
+ ### Browser Redirect
1502
+
1503
+ You can trigger a browser redirect with the `redirect` helper method:
1504
+
1505
+ ```ruby
1506
+ get '/foo' do
1507
+ redirect to('/bar')
1508
+ end
1509
+ ```
1510
+
1511
+ Any additional parameters are handled like arguments passed to `halt`:
1512
+
1513
+ ```ruby
1514
+ redirect to('/bar'), 303
1515
+ redirect 'http://www.google.com/', 'wrong place, buddy'
1516
+ ```
1517
+
1518
+ You can also easily redirect back to the page the user came from with
1519
+ `redirect back`:
1520
+
1521
+ ```ruby
1522
+ get '/foo' do
1523
+ "<a href='/bar'>do something</a>"
1524
+ end
1525
+
1526
+ get '/bar' do
1527
+ do_something
1528
+ redirect back
1529
+ end
1530
+ ```
1531
+
1532
+ To pass arguments with a redirect, either add them to the query:
1533
+
1534
+ ```ruby
1535
+ redirect to('/bar?sum=42')
1536
+ ```
1537
+
1538
+ Or use a session:
1539
+
1540
+ ```ruby
1541
+ enable :sessions
1542
+
1543
+ get '/foo' do
1544
+ session[:secret] = 'foo'
1545
+ redirect to('/bar')
1546
+ end
1547
+
1548
+ get '/bar' do
1549
+ session[:secret]
1550
+ end
1551
+ ```
1552
+
1553
+ ### Cache Control
1554
+
1555
+ Setting your headers correctly is the foundation for proper HTTP caching.
1556
+
1557
+ You can easily set the Cache-Control header like this:
1558
+
1559
+ ```ruby
1560
+ get '/' do
1561
+ cache_control :public
1562
+ "cache it!"
1563
+ end
1564
+ ```
1565
+
1566
+ Pro tip: Set up caching in a before filter:
1567
+
1568
+ ```ruby
1569
+ before do
1570
+ cache_control :public, :must_revalidate, :max_age => 60
1571
+ end
1572
+ ```
1573
+
1574
+ If you are using the `expires` helper to set the corresponding header,
1575
+ `Cache-Control` will be set automatically for you:
1576
+
1577
+ ```ruby
1578
+ before do
1579
+ expires 500, :public, :must_revalidate
1580
+ end
1581
+ ```
1582
+
1583
+ To properly use caches, you should consider using `etag` or `last_modified`.
1584
+ It is recommended to call those helpers *before* doing any heavy lifting, as
1585
+ they will immediately flush a response if the client already has the current
1586
+ version in its cache:
1587
+
1588
+ ```ruby
1589
+ get "/article/:id" do
1590
+ @article = Article.find params['id']
1591
+ last_modified @article.updated_at
1592
+ etag @article.sha1
1593
+ erb :article
1594
+ end
1595
+ ```
1596
+
1597
+ It is also possible to use a
1598
+ [weak ETag](https://en.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation):
1599
+
1600
+ ```ruby
1601
+ etag @article.sha1, :weak
1602
+ ```
1603
+
1604
+ These helpers will not do any caching for you, but rather feed the necessary
1605
+ information to your cache. If you are looking for a quick
1606
+ reverse-proxy caching solution, try
1607
+ [rack-cache](https://github.com/rtomayko/rack-cache#readme):
1608
+
1609
+ ```ruby
1610
+ require "rack/cache"
1611
+ require "sinatra"
1612
+
1613
+ use Rack::Cache
1614
+
1615
+ get '/' do
1616
+ cache_control :public, :max_age => 36000
1617
+ sleep 5
1618
+ "hello"
1619
+ end
1620
+ ```
1621
+
1622
+ Use the `:static_cache_control` setting (see [below](#cache-control)) to add
1623
+ `Cache-Control` header info to static files.
1624
+
1625
+ According to RFC 2616, your application should behave differently if the
1626
+ If-Match or If-None-Match header is set to `*`, depending on whether the
1627
+ resource requested is already in existence. Sinatra assumes resources for
1628
+ safe (like get) and idempotent (like put) requests are already in existence,
1629
+ whereas other resources (for instance post requests) are treated as new
1630
+ resources. You can change this behavior by passing in a `:new_resource`
1631
+ option:
1632
+
1633
+ ```ruby
1634
+ get '/create' do
1635
+ etag '', :new_resource => true
1636
+ Article.create
1637
+ erb :new_article
1638
+ end
1639
+ ```
1640
+
1641
+ If you still want to use a weak ETag, pass in a `:kind` option:
1642
+
1643
+ ```ruby
1644
+ etag '', :new_resource => true, :kind => :weak
1645
+ ```
1646
+
1647
+ ### Sending Files
1648
+
1649
+ To return the contents of a file as the response, you can use the `send_file`
1650
+ helper method:
1651
+
1652
+ ```ruby
1653
+ get '/' do
1654
+ send_file 'foo.png'
1655
+ end
1656
+ ```
1657
+
1658
+ It also takes options:
1659
+
1660
+ ```ruby
1661
+ send_file 'foo.png', :type => :jpg
1662
+ ```
1663
+
1664
+ The options are:
1665
+
1666
+ <dl>
1667
+ <dt>filename</dt>
1668
+ <dd>File name to be used in the response,
1669
+ defaults to the real file name.</dd>
1670
+ <dt>last_modified</dt>
1671
+ <dd>Value for Last-Modified header, defaults to the file's mtime.</dd>
1672
+
1673
+ <dt>type</dt>
1674
+ <dd>Value for Content-Type header, guessed from the file extension if
1675
+ missing.</dd>
1676
+
1677
+ <dt>disposition</dt>
1678
+ <dd>
1679
+ Value for Content-Disposition header, possible values: <tt>nil</tt>
1680
+ (default), <tt>:attachment</tt> and <tt>:inline</tt>
1681
+ </dd>
1682
+
1683
+ <dt>length</dt>
1684
+ <dd>Value for Content-Length header, defaults to file size.</dd>
1685
+
1686
+ <dt>status</dt>
1687
+ <dd>
1688
+ Status code to be sent. Useful when sending a static file as an error
1689
+ page. If supported by the Rack handler, other means than streaming
1690
+ from the Ruby process will be used. If you use this helper method,
1691
+ Sinatra will automatically handle range requests.
1692
+ </dd>
1693
+ </dl>
1694
+
1695
+ ### Accessing the Request Object
1696
+
1697
+ The incoming request object can be accessed from request level (filter,
1698
+ routes, error handlers) through the `request` method:
1699
+
1700
+ ```ruby
1701
+ # app running on http://example.com/example
1702
+ get '/foo' do
1703
+ t = %w[text/css text/html application/javascript]
1704
+ request.accept # ['text/html', '*/*']
1705
+ request.accept? 'text/xml' # true
1706
+ request.preferred_type(t) # 'text/html'
1707
+ request.body # request body sent by the client (see below)
1708
+ request.scheme # "http"
1709
+ request.script_name # "/example"
1710
+ request.path_info # "/foo"
1711
+ request.port # 80
1712
+ request.request_method # "GET"
1713
+ request.query_string # ""
1714
+ request.content_length # length of request.body
1715
+ request.media_type # media type of request.body
1716
+ request.host # "example.com"
1717
+ request.get? # true (similar methods for other verbs)
1718
+ request.form_data? # false
1719
+ request["some_param"] # value of some_param parameter. [] is a shortcut to the params hash.
1720
+ request.referrer # the referrer of the client or '/'
1721
+ request.user_agent # user agent (used by :agent condition)
1722
+ request.cookies # hash of browser cookies
1723
+ request.xhr? # is this an ajax request?
1724
+ request.url # "http://example.com/example/foo"
1725
+ request.path # "/example/foo"
1726
+ request.ip # client IP address
1727
+ request.secure? # false (would be true over ssl)
1728
+ request.forwarded? # true (if running behind a reverse proxy)
1729
+ request.env # raw env hash handed in by Rack
1730
+ end
1731
+ ```
1732
+
1733
+ Some options, like `script_name` or `path_info`, can also be written:
1734
+
1735
+ ```ruby
1736
+ before { request.path_info = "/" }
1737
+
1738
+ get "/" do
1739
+ "all requests end up here"
1740
+ end
1741
+ ```
1742
+
1743
+ The `request.body` is an IO or StringIO object:
1744
+
1745
+ ```ruby
1746
+ post "/api" do
1747
+ request.body.rewind # in case someone already read it
1748
+ data = JSON.parse request.body.read
1749
+ "Hello #{data['name']}!"
1750
+ end
1751
+ ```
1752
+
1753
+ ### Attachments
1754
+
1755
+ You can use the `attachment` helper to tell the browser the response should
1756
+ be stored on disk rather than displayed in the browser:
1757
+
1758
+ ```ruby
1759
+ get '/' do
1760
+ attachment
1761
+ "store it!"
1762
+ end
1763
+ ```
1764
+
1765
+ You can also pass it a file name:
1766
+
1767
+ ```ruby
1768
+ get '/' do
1769
+ attachment "info.txt"
1770
+ "store it!"
1771
+ end
1772
+ ```
1773
+
1774
+ ### Dealing with Date and Time
1775
+
1776
+ Sinatra offers a `time_for` helper method that generates a Time object from
1777
+ the given value. It is also able to convert `DateTime`, `Date` and similar
1778
+ classes:
1779
+
1780
+ ```ruby
1781
+ get '/' do
1782
+ pass if Time.now > time_for('Dec 23, 2016')
1783
+ "still time"
1784
+ end
1785
+ ```
1786
+
1787
+ This method is used internally by `expires`, `last_modified` and akin. You
1788
+ can therefore easily extend the behavior of those methods by overriding
1789
+ `time_for` in your application:
1790
+
1791
+ ```ruby
1792
+ helpers do
1793
+ def time_for(value)
1794
+ case value
1795
+ when :yesterday then Time.now - 24*60*60
1796
+ when :tomorrow then Time.now + 24*60*60
1797
+ else super
1798
+ end
1799
+ end
1800
+ end
1801
+
1802
+ get '/' do
1803
+ last_modified :yesterday
1804
+ expires :tomorrow
1805
+ "hello"
1806
+ end
1807
+ ```
1808
+
1809
+ ### Looking Up Template Files
1810
+
1811
+ The `find_template` helper is used to find template files for rendering:
1812
+
1813
+ ```ruby
1814
+ find_template settings.views, 'foo', Tilt[:haml] do |file|
1815
+ puts "could be #{file}"
1816
+ end
1817
+ ```
1818
+
1819
+ This is not really useful. But it is useful that you can actually override
1820
+ this method to hook in your own lookup mechanism. For instance, if you want
1821
+ to be able to use more than one view directory:
1822
+
1823
+ ```ruby
1824
+ set :views, ['views', 'templates']
1825
+
1826
+ helpers do
1827
+ def find_template(views, name, engine, &block)
1828
+ Array(views).each { |v| super(v, name, engine, &block) }
1829
+ end
1830
+ end
1831
+ ```
1832
+
1833
+ Another example would be using different directories for different engines:
1834
+
1835
+ ```ruby
1836
+ set :views, :haml => 'templates', :default => 'views'
1837
+
1838
+ helpers do
1839
+ def find_template(views, name, engine, &block)
1840
+ _, folder = views.detect { |k,v| engine == Tilt[k] }
1841
+ folder ||= views[:default]
1842
+ super(folder, name, engine, &block)
1843
+ end
1844
+ end
1845
+ ```
1846
+
1847
+ You can also easily wrap this up in an extension and share it with others!
1848
+
1849
+ Note that `find_template` does not check if the file really exists but
1850
+ rather calls the given block for all possible paths. This is not a
1851
+ performance issue, since `render` will use `break` as soon as a file is
1852
+ found. Also, template locations (and content) will be cached if you are not
1853
+ running in development mode. You should keep that in mind if you write a
1854
+ really crazy method.
1855
+
1856
+ ## Configuration
1857
+
1858
+ Run once, at startup, in any environment:
1859
+
1860
+ ```ruby
1861
+ configure do
1862
+ # setting one option
1863
+ set :option, 'value'
1864
+
1865
+ # setting multiple options
1866
+ set :a => 1, :b => 2
1867
+
1868
+ # same as `set :option, true`
1869
+ enable :option
1870
+
1871
+ # same as `set :option, false`
1872
+ disable :option
1873
+
1874
+ # you can also have dynamic settings with blocks
1875
+ set(:css_dir) { File.join(views, 'css') }
1876
+ end
1877
+ ```
1878
+
1879
+ Run only when the environment (`APP_ENV` environment variable) is set to
1880
+ `:production`:
1881
+
1882
+ ```ruby
1883
+ configure :production do
1884
+ ...
1885
+ end
1886
+ ```
1887
+
1888
+ Run when the environment is set to either `:production` or `:test`:
1889
+
1890
+ ```ruby
1891
+ configure :production, :test do
1892
+ ...
1893
+ end
1894
+ ```
1895
+
1896
+ You can access those options via `settings`:
1897
+
1898
+ ```ruby
1899
+ configure do
1900
+ set :foo, 'bar'
1901
+ end
1902
+
1903
+ get '/' do
1904
+ settings.foo? # => true
1905
+ settings.foo # => 'bar'
1906
+ ...
1907
+ end
1908
+ ```
1909
+
1910
+ ### Configuring attack protection
1911
+
1912
+ Sinatra is using
1913
+ [Rack::Protection](https://github.com/sinatra/sinatra/tree/main/rack-protection#readme) to
1914
+ defend your application against common, opportunistic attacks. You can
1915
+ easily disable this behavior (which will open up your application to tons
1916
+ of common vulnerabilities):
1917
+
1918
+ ```ruby
1919
+ disable :protection
1920
+ ```
1921
+
1922
+ To skip a single defense layer, set `protection` to an options hash:
1923
+
1924
+ ```ruby
1925
+ set :protection, :except => :path_traversal
1926
+ ```
1927
+ You can also hand in an array in order to disable a list of protections:
1928
+
1929
+ ```ruby
1930
+ set :protection, :except => [:path_traversal, :remote_token]
1931
+ ```
1932
+
1933
+ By default, Sinatra will only set up session based protection if `:sessions`
1934
+ have been enabled. See '[Using Sessions](#using-sessions)'. Sometimes you may want to set up
1935
+ sessions "outside" of the Sinatra app, such as in the config.ru or with a
1936
+ separate `Rack::Builder` instance. In that case, you can still set up session
1937
+ based protection by passing the `:session` option:
1938
+
1939
+ ```ruby
1940
+ set :protection, :session => true
1941
+ ```
1942
+
1943
+ ### Available Settings
1944
+
1945
+ <dl>
1946
+ <dt>absolute_redirects</dt>
1947
+ <dd>
1948
+ If disabled, Sinatra will allow relative redirects, however, Sinatra
1949
+ will no longer conform with RFC 2616 (HTTP 1.1), which only allows
1950
+ absolute redirects.
1951
+ </dd>
1952
+ <dd>
1953
+ Enable if your app is running behind a reverse proxy that has not been
1954
+ set up properly. Note that the <tt>url</tt> helper will still produce
1955
+ absolute URLs, unless you pass in <tt>false</tt> as the second
1956
+ parameter.
1957
+ </dd>
1958
+ <dd>Disabled by default.</dd>
1959
+
1960
+ <dt>add_charset</dt>
1961
+ <dd>
1962
+ Mime types the <tt>content_type</tt> helper will automatically add the
1963
+ charset info to. You should add to it rather than overriding this
1964
+ option: <tt>settings.add_charset << "application/foobar"</tt>
1965
+ </dd>
1966
+
1967
+ <dt>app_file</dt>
1968
+ <dd>
1969
+ Path to the main application file, used to detect project root, views
1970
+ and public folder and inline templates.
1971
+ </dd>
1972
+
1973
+ <dt>bind</dt>
1974
+ <dd>
1975
+ IP address to bind to (default: <tt>0.0.0.0</tt> <em>or</em>
1976
+ <tt>localhost</tt> if your `environment` is set to development). Only
1977
+ used for built-in server.
1978
+ </dd>
1979
+
1980
+ <dt>default_content_type</dt>
1981
+ <dd>
1982
+ Content-Type to assume if unknown (defaults to <tt>"text/html"</tt>). Set
1983
+ to <tt>nil</tt> to not set a default Content-Type on every response; when
1984
+ configured so, you must set the Content-Type manually when emitting content
1985
+ or the user-agent will have to sniff it (or, if <tt>nosniff</tt> is enabled
1986
+ in Rack::Protection::XSSHeader, assume <tt>application/octet-stream</tt>).
1987
+ </dd>
1988
+
1989
+ <dt>default_encoding</dt>
1990
+ <dd>Encoding to assume if unknown (defaults to <tt>"utf-8"</tt>).</dd>
1991
+
1992
+ <dt>dump_errors</dt>
1993
+ <dd>Display errors in the log. Enabled by default unless environment is "test".</dd>
1994
+
1995
+ <dt>environment</dt>
1996
+ <dd>
1997
+ Current environment. Defaults to <tt>ENV['APP_ENV']</tt>, or
1998
+ <tt>"development"</tt> if not available.
1999
+ </dd>
2000
+
2001
+ <dt>host_authorization</dt>
2002
+ <dd>
2003
+ <p>
2004
+ You can pass a hash of options to <tt>host_authorization</tt>,
2005
+ to be used by the <tt>Rack::Protection::HostAuthorization</tt> middleware.
2006
+ </p>
2007
+ <p>
2008
+ The middleware can block requests with unrecognized hostnames, to prevent DNS rebinding
2009
+ and other host header attacks. It checks the <tt>Host</tt>, <tt>X-Forwarded-Host</tt>
2010
+ and <tt>Forwarded</tt> headers.
2011
+ </p>
2012
+ <p>
2013
+ Useful options are:
2014
+ <ul>
2015
+ <li><tt>permitted_hosts</tt> – an array of hostnames (and <tt>IPAddr</tt> objects) your app recognizes
2016
+ <ul>
2017
+ <li>in the <tt>development</tt> environment, it is set to <tt>.localhost</tt>, <tt>.test</tt> and any IPv4/IPv6 address</li>
2018
+ <li>if empty, any hostname is permitted (the default for any other environment)</li>
2019
+ </ul>
2020
+ </li>
2021
+ <li><tt>status</tt> – the HTTP status code used in the response when a request is blocked (defaults to <tt>403</tt>)</li>
2022
+ <li><tt>message</tt> – the body used in the response when a request is blocked (defaults to <tt>Host not permitted</tt>)</li>
2023
+ <li><tt>allow_if</tt> – supply a <tt>Proc</tt> to use custom allow/deny logic, the proc is passed the request environment</li>
2024
+ </ul>
2025
+ </p>
2026
+ </dd>
2027
+
2028
+ <dt>logging</dt>
2029
+ <dd>Use the logger.</dd>
2030
+
2031
+ <dt>lock</dt>
2032
+ <dd>
2033
+ Places a lock around every request, only running processing on request
2034
+ per Ruby process concurrently.
2035
+ </dd>
2036
+ <dd>Enabled if your app is not thread-safe. Disabled by default.</dd>
2037
+
2038
+ <dt>method_override</dt>
2039
+ <dd>
2040
+ Use <tt>_method</tt> magic to allow put/delete forms in browsers that
2041
+ don't support it.
2042
+ </dd>
2043
+
2044
+ <dt>mustermann_opts</dt>
2045
+ <dd>
2046
+ A default hash of options to pass to Mustermann.new when compiling routing
2047
+ paths.
2048
+ </dd>
2049
+
2050
+ <dt>port</dt>
2051
+ <dd>Port to listen on. Only used for built-in server.</dd>
2052
+
2053
+ <dt>prefixed_redirects</dt>
2054
+ <dd>
2055
+ Whether or not to insert <tt>request.script_name</tt> into redirects
2056
+ if no absolute path is given. That way <tt>redirect '/foo'</tt> would
2057
+ behave like <tt>redirect to('/foo')</tt>. Disabled by default.
2058
+ </dd>
2059
+
2060
+ <dt>protection</dt>
2061
+ <dd>
2062
+ Whether or not to enable web attack protections. See protection section
2063
+ above.
2064
+ </dd>
2065
+
2066
+ <dt>public_dir</dt>
2067
+ <dd>Alias for <tt>public_folder</tt>. See below.</dd>
2068
+
2069
+ <dt>public_folder</dt>
2070
+ <dd>
2071
+ Path to the folder public files are served from. Only used if static
2072
+ file serving is enabled (see <tt>static</tt> setting below). Inferred
2073
+ from <tt>app_file</tt> setting if not set.
2074
+ </dd>
2075
+
2076
+ <dt>quiet</dt>
2077
+ <dd>
2078
+ Disables logs generated by Sinatra's start and stop commands.
2079
+ <tt>false</tt> by default.
2080
+ </dd>
2081
+
2082
+ <dt>reload_templates</dt>
2083
+ <dd>
2084
+ Whether or not to reload templates between requests. Enabled in
2085
+ development mode.
2086
+ </dd>
2087
+
2088
+ <dt>root</dt>
2089
+ <dd>
2090
+ Path to project root folder. Inferred from <tt>app_file</tt> setting
2091
+ if not set.
2092
+ </dd>
2093
+
2094
+ <dt>raise_errors</dt>
2095
+ <dd>
2096
+ Raise unhandled errors (will stop application). Enabled by default when
2097
+ <tt>environment</tt> is set to <tt>"test"</tt>, disabled otherwise.
2098
+ </dd>
2099
+ <dd>
2100
+ Any explicitly defined error handlers always override this setting. See
2101
+ the "Error" section below.
2102
+ </dd>
2103
+
2104
+ <dt>run</dt>
2105
+ <dd>
2106
+ If enabled, Sinatra will handle starting the web server. Do not
2107
+ enable if using rackup or other means.
2108
+ </dd>
2109
+
2110
+ <dt>running</dt>
2111
+ <dd>Is the built-in server running now? Do not change this setting!</dd>
2112
+
2113
+ <dt>server</dt>
2114
+ <dd>
2115
+ Server or list of servers to use for built-in server. Order indicates
2116
+ priority, default depends on Ruby implementation.
2117
+ </dd>
2118
+
2119
+ <dt>server_settings</dt>
2120
+ <dd>
2121
+ You can pass a hash of options to <tt>server_settings</tt>,
2122
+ such as <tt>Host</tt> or <tt>Port</tt>.
2123
+ </dd>
2124
+
2125
+ <dt>sessions</dt>
2126
+ <dd>
2127
+ Enable cookie-based sessions support using
2128
+ <tt>Rack::Session::Cookie</tt>. See 'Using Sessions' section for more
2129
+ information.
2130
+ </dd>
2131
+
2132
+ <dt>session_store</dt>
2133
+ <dd>
2134
+ The Rack session middleware used. Defaults to
2135
+ <tt>Rack::Session::Cookie</tt>. See 'Using Sessions' section for more
2136
+ information.
2137
+ </dd>
2138
+
2139
+ <dt>show_exceptions</dt>
2140
+ <dd>
2141
+ Show a stack trace in the browser when an exception happens. Enabled by
2142
+ default when <tt>environment</tt> is set to <tt>"development"</tt>,
2143
+ disabled otherwise.
2144
+ </dd>
2145
+ <dd>
2146
+ Can also be set to <tt>:after_handler</tt> to trigger app-specified
2147
+ error handling before showing a stack trace in the browser.
2148
+ </dd>
2149
+
2150
+ <dt>static</dt>
2151
+ <dd>Whether Sinatra should handle serving static files.</dd>
2152
+ <dd>Disable when using a server able to do this on its own.</dd>
2153
+ <dd>Disabling will boost performance.</dd>
2154
+ <dd>
2155
+ Enabled by default in classic style, disabled for modular apps.
2156
+ </dd>
2157
+
2158
+ <dt>static_cache_control</dt>
2159
+ <dd>
2160
+ When Sinatra is serving static files, set this to add
2161
+ <tt>Cache-Control</tt> headers to the responses. Uses the
2162
+ <tt>cache_control</tt> helper. Disabled by default.
2163
+ </dd>
2164
+ <dd>
2165
+ Use an explicit array when setting multiple values:
2166
+ <tt>set :static_cache_control, [:public, :max_age => 300]</tt>
2167
+ </dd>
2168
+
2169
+ <dt>static_headers</dt>
2170
+ <dd>
2171
+ Allows you to define custom header settings for static file responses.
2172
+ </dd>
2173
+ <dd>
2174
+ For example: <br>
2175
+ <tt>set :static_headers, {'access-control-allow-origin' => '*', 'x-static-asset' => 'served-by-sinatra'}</tt>
2176
+ </dd>
2177
+
2178
+
2179
+ <dt>threaded</dt>
2180
+ <dd>
2181
+ If set to <tt>true</tt>, will tell server to use
2182
+ <tt>EventMachine.defer</tt> for processing the request.
2183
+ </dd>
2184
+
2185
+ <dt>traps</dt>
2186
+ <dd>Whether Sinatra should handle system signals.</dd>
2187
+
2188
+ <dt>views</dt>
2189
+ <dd>
2190
+ Path to the views folder. Inferred from <tt>app_file</tt> setting if
2191
+ not set.
2192
+ </dd>
2193
+
2194
+ <dt>x_cascade</dt>
2195
+ <dd>
2196
+ Whether or not to set the X-Cascade header if no route matches.
2197
+ Defaults to <tt>true</tt>.
2198
+ </dd>
2199
+ </dl>
2200
+
2201
+ ## Lifecycle Events
2202
+
2203
+ There are 2 lifecycle events currently exposed by Sinatra. One when the server starts and one when it stops.
2204
+
2205
+ They can be used like this:
2206
+
2207
+ ```ruby
2208
+ on_start do
2209
+ puts "===== Booting up ====="
2210
+ end
2211
+
2212
+ on_stop do
2213
+ puts "===== Shutting down ====="
2214
+ end
2215
+ ```
2216
+
2217
+ Note that these callbacks only work when using Sinatra to start the web server.
2218
+
2219
+ ## Environments
2220
+
2221
+ There are three predefined `environments`: `"development"`,
2222
+ `"production"` and `"test"`. Environments can be set through the
2223
+ `APP_ENV` environment variable. The default value is `"development"`.
2224
+ In the `"development"` environment all templates are reloaded between
2225
+ requests, and special `not_found` and `error` handlers display stack
2226
+ traces in your browser. In the `"production"` and `"test"` environments,
2227
+ templates are cached by default.
2228
+
2229
+ To run different environments, set the `APP_ENV` environment variable:
2230
+
2231
+ ```shell
2232
+ APP_ENV=production ruby my_app.rb
2233
+ ```
2234
+
2235
+ You can use predefined methods: `development?`, `test?` and `production?` to
2236
+ check the current environment setting:
2237
+
2238
+ ```ruby
2239
+ get '/' do
2240
+ if settings.development?
2241
+ "development!"
2242
+ else
2243
+ "not development!"
2244
+ end
2245
+ end
2246
+ ```
2247
+
2248
+ ## Error Handling
2249
+
2250
+ Error handlers run within the same context as routes and before filters,
2251
+ which means you get all the goodies it has to offer, like `haml`, `erb`,
2252
+ `halt`, etc.
2253
+
2254
+ ### Not Found
2255
+
2256
+ When a `Sinatra::NotFound` exception is raised, or the response's status
2257
+ code is 404, the `not_found` handler is invoked:
2258
+
2259
+ ```ruby
2260
+ not_found do
2261
+ 'This is nowhere to be found.'
2262
+ end
2263
+ ```
2264
+
2265
+ ### Error
2266
+
2267
+ The `error` handler is invoked any time an exception is raised from a route
2268
+ block or a filter. But note in development it will only run if you set the
2269
+ show exceptions option to `:after_handler`:
2270
+
2271
+ ```ruby
2272
+ set :show_exceptions, :after_handler
2273
+ ```
2274
+
2275
+ A catch-all error handler can be defined with `error` and a block:
2276
+
2277
+ ```ruby
2278
+ error do
2279
+ 'Sorry there was a nasty error'
2280
+ end
2281
+ ```
2282
+
2283
+ The exception object can be obtained from the `sinatra.error` Rack variable:
2284
+
2285
+ ```ruby
2286
+ error do
2287
+ 'Sorry there was a nasty error - ' + env['sinatra.error'].message
2288
+ end
2289
+ ```
2290
+
2291
+ Pass an error class as an argument to create handlers for custom errors:
2292
+
2293
+ ```ruby
2294
+ error MyCustomError do
2295
+ 'So what happened was...' + env['sinatra.error'].message
2296
+ end
2297
+ ```
2298
+
2299
+ Then, if this happens:
2300
+
2301
+ ```ruby
2302
+ get '/' do
2303
+ raise MyCustomError, 'something bad'
2304
+ end
2305
+ ```
2306
+
2307
+ You get this:
2308
+
2309
+ ```
2310
+ So what happened was... something bad
2311
+ ```
2312
+
2313
+ Alternatively, you can install an error handler for a status code:
2314
+
2315
+ ```ruby
2316
+ error 403 do
2317
+ 'Access forbidden'
2318
+ end
2319
+
2320
+ get '/secret' do
2321
+ 403
2322
+ end
2323
+ ```
2324
+
2325
+ Or a range:
2326
+
2327
+ ```ruby
2328
+ error 400..510 do
2329
+ 'Boom'
2330
+ end
2331
+ ```
2332
+
2333
+ Sinatra installs special `not_found` and `error` handlers when
2334
+ running under the development environment to display nice stack traces
2335
+ and additional debugging information in your browser.
2336
+
2337
+ ### Behavior with `raise_errors` option
2338
+
2339
+ When `raise_errors` option is `true`, errors that are unhandled are raised
2340
+ outside of the application. Additionally, any errors that would have been
2341
+ caught by the catch-all error handler are raised.
2342
+
2343
+ For example, consider the following configuration:
2344
+
2345
+ ```ruby
2346
+ # First handler
2347
+ error MyCustomError do
2348
+ 'A custom message'
2349
+ end
2350
+
2351
+ # Second handler
2352
+ error do
2353
+ 'A catch-all message'
2354
+ end
2355
+ ```
2356
+
2357
+ If `raise_errors` is `false`:
2358
+
2359
+ * When `MyCustomError` or descendant is raised, the first handler is invoked.
2360
+ The HTTP response body will contain `"A custom message"`.
2361
+ * When any other error is raised, the second handler is invoked. The HTTP
2362
+ response body will contain `"A catch-all message"`.
2363
+
2364
+ If `raise_errors` is `true`:
2365
+
2366
+ * When `MyCustomError` or descendant is raised, the behavior is identical to
2367
+ when `raise_errors` is `false`, described above.
2368
+ * When any other error is raised, the second handler is *not* invoked, and
2369
+ the error is raised outside of the application.
2370
+ * If the environment is `production`, the HTTP response body will contain
2371
+ a generic error message, e.g. `"An unhandled lowlevel error occurred. The
2372
+ application logs may have details."`
2373
+ * If the environment is not `production`, the HTTP response body will contain
2374
+ the verbose error backtrace.
2375
+ * Regardless of environment, if `show_exceptions` is set to `:after_handler`,
2376
+ the HTTP response body will contain the verbose error backtrace.
2377
+
2378
+ In the `test` environment, `raise_errors` is set to `true` by default. This
2379
+ means that in order to write a test for a catch-all error handler,
2380
+ `raise_errors` must temporarily be set to `false` for that particular test.
2381
+
2382
+ ## Rack Middleware
2383
+
2384
+ Sinatra rides on [Rack](https://rack.github.io/), a minimal standard
2385
+ interface for Ruby web frameworks. One of Rack's most interesting
2386
+ capabilities for application developers is support for "middleware" --
2387
+ components that sit between the server and your application monitoring
2388
+ and/or manipulating the HTTP request/response to provide various types
2389
+ of common functionality.
2390
+
2391
+ Sinatra makes building Rack middleware pipelines a cinch via a top-level
2392
+ `use` method:
2393
+
2394
+ ```ruby
2395
+ require 'sinatra'
2396
+ require 'my_custom_middleware'
2397
+
2398
+ use Rack::Lint
2399
+ use MyCustomMiddleware
2400
+
2401
+ get '/hello' do
2402
+ 'Hello World'
2403
+ end
2404
+ ```
2405
+
2406
+ The semantics of `use` are identical to those defined for the
2407
+ [Rack::Builder](https://www.rubydoc.info/github/rack/rack/main/Rack/Builder) DSL
2408
+ (most frequently used from rackup files). For example, the `use` method
2409
+ accepts multiple/variable args as well as blocks:
2410
+
2411
+ ```ruby
2412
+ use Rack::Auth::Basic do |username, password|
2413
+ username == 'admin' && password == 'secret'
2414
+ end
2415
+ ```
2416
+
2417
+ Rack is distributed with a variety of standard middleware for logging,
2418
+ debugging, URL routing, authentication, and session handling. Sinatra uses
2419
+ many of these components automatically based on configuration so you
2420
+ typically don't have to `use` them explicitly.
2421
+
2422
+ You can find useful middleware in
2423
+ [rack](https://github.com/rack/rack/tree/main/lib/rack),
2424
+ [rack-contrib](https://github.com/rack/rack-contrib#readme),
2425
+ or in the [Rack wiki](https://github.com/rack/rack/wiki/List-of-Middleware).
2426
+
2427
+ ## Testing
2428
+
2429
+ Sinatra tests can be written using any Rack-based testing library or
2430
+ framework.
2431
+ [Rack::Test](https://www.rubydoc.info/github/rack/rack-test/main/frames)
2432
+ is recommended:
2433
+
2434
+ ```ruby
2435
+ require 'my_sinatra_app'
2436
+ require 'minitest/autorun'
2437
+ require 'rack/test'
2438
+
2439
+ class MyAppTest < Minitest::Test
2440
+ include Rack::Test::Methods
2441
+
2442
+ def app
2443
+ Sinatra::Application
2444
+ end
2445
+
2446
+ def test_my_default
2447
+ get '/'
2448
+ assert_equal 'Hello World!', last_response.body
2449
+ end
2450
+
2451
+ def test_with_params
2452
+ get '/meet', :name => 'Frank'
2453
+ assert_equal 'Hello Frank!', last_response.body
2454
+ end
2455
+
2456
+ def test_with_user_agent
2457
+ get '/', {}, 'HTTP_USER_AGENT' => 'Songbird'
2458
+ assert_equal "You're using Songbird!", last_response.body
2459
+ end
2460
+ end
2461
+ ```
2462
+
2463
+ Note: If you are using Sinatra in the modular style, replace
2464
+ `Sinatra::Application` above with the class name of your app.
2465
+
2466
+ ## Sinatra::Base - Middleware, Libraries, and Modular Apps
2467
+
2468
+ Defining your app at the top-level works well for micro-apps but has
2469
+ considerable drawbacks when building reusable components such as Rack
2470
+ middleware, Rails metal, simple libraries with a server component, or even
2471
+ Sinatra extensions. The top-level assumes a micro-app style configuration
2472
+ (e.g., a single application file, `./public` and `./views`
2473
+ directories, logging, exception detail page, etc.). That's where
2474
+ `Sinatra::Base` comes into play:
2475
+
2476
+ ```ruby
2477
+ require 'sinatra/base'
2478
+
2479
+ class MyApp < Sinatra::Base
2480
+ set :sessions, true
2481
+ set :foo, 'bar'
2482
+
2483
+ get '/' do
2484
+ 'Hello world!'
2485
+ end
2486
+ end
2487
+ ```
2488
+
2489
+ The methods available to `Sinatra::Base` subclasses are exactly the same
2490
+ as those available via the top-level DSL. Most top-level apps can be
2491
+ converted to `Sinatra::Base` components with two modifications:
2492
+
2493
+ * Your file should require `sinatra/base` instead of `sinatra`;
2494
+ otherwise, all of Sinatra's DSL methods are imported into the main
2495
+ namespace.
2496
+ * Put your app's routes, error handlers, filters, and options in a subclass
2497
+ of `Sinatra::Base`.
2498
+
2499
+ `Sinatra::Base` is a blank slate. Most options are disabled by default,
2500
+ including the built-in server. See [Configuring
2501
+ Settings](http://www.sinatrarb.com/configuration.html) for details on
2502
+ available options and their behavior. If you want behavior more similar
2503
+ to when you define your app at the top level (also known as Classic
2504
+ style), you can subclass `Sinatra::Application`:
2505
+
2506
+ ```ruby
2507
+ require 'sinatra/base'
2508
+
2509
+ class MyApp < Sinatra::Application
2510
+ get '/' do
2511
+ 'Hello world!'
2512
+ end
2513
+ end
2514
+ ```
2515
+
2516
+ ### Modular vs. Classic Style
2517
+
2518
+ Contrary to common belief, there is nothing wrong with the classic
2519
+ style. If it suits your application, you do not have to switch to a
2520
+ modular application.
2521
+
2522
+ The main disadvantage of using the classic style rather than the modular
2523
+ style is that you will only have one Sinatra application per Ruby
2524
+ process. If you plan to use more than one, switch to the modular style.
2525
+ There is no reason you cannot mix the modular and classic styles.
2526
+
2527
+ If switching from one style to the other, you should be aware of
2528
+ slightly different default settings:
2529
+
2530
+ <table>
2531
+ <tr>
2532
+ <th>Setting</th>
2533
+ <th>Classic</th>
2534
+ <th>Modular</th>
2535
+ <th>Modular</th>
2536
+ </tr>
2537
+
2538
+ <tr>
2539
+ <td>app_file</td>
2540
+ <td>file loading sinatra</td>
2541
+ <td>file subclassing Sinatra::Base</td>
2542
+ <td>file subclassing Sinatra::Application</td>
2543
+ </tr>
2544
+
2545
+ <tr>
2546
+ <td>run</td>
2547
+ <td>$0 == app_file</td>
2548
+ <td>false</td>
2549
+ <td>false</td>
2550
+ </tr>
2551
+
2552
+ <tr>
2553
+ <td>logging</td>
2554
+ <td>true</td>
2555
+ <td>false</td>
2556
+ <td>true</td>
2557
+ </tr>
2558
+
2559
+ <tr>
2560
+ <td>method_override</td>
2561
+ <td>true</td>
2562
+ <td>false</td>
2563
+ <td>true</td>
2564
+ </tr>
2565
+
2566
+ <tr>
2567
+ <td>inline_templates</td>
2568
+ <td>true</td>
2569
+ <td>false</td>
2570
+ <td>true</td>
2571
+ </tr>
2572
+
2573
+ <tr>
2574
+ <td>static</td>
2575
+ <td>true</td>
2576
+ <td>File.exist?(public_folder)</td>
2577
+ <td>true</td>
2578
+ </tr>
2579
+ </table>
2580
+
2581
+ ### Serving a Modular Application
2582
+
2583
+ There are two common options for starting a modular app, actively
2584
+ starting with `run!`:
2585
+
2586
+ ```ruby
2587
+ # my_app.rb
2588
+ require 'sinatra/base'
2589
+
2590
+ class MyApp < Sinatra::Base
2591
+ # ... app code here ...
2592
+
2593
+ # start the server if ruby file executed directly
2594
+ run! if app_file == $0
2595
+ end
2596
+ ```
2597
+
2598
+ Start with:
2599
+
2600
+ ```shell
2601
+ ruby my_app.rb
2602
+ ```
2603
+
2604
+ Or with a `config.ru` file, which allows using any Rack handler:
2605
+
2606
+ ```ruby
2607
+ # config.ru (run with rackup)
2608
+ require './my_app'
2609
+ run MyApp
2610
+ ```
2611
+
2612
+ Run:
2613
+
2614
+ ```shell
2615
+ rackup -p 4567
2616
+ ```
2617
+
2618
+ ### Using a Classic Style Application with a config.ru
2619
+
2620
+ Write your app file:
2621
+
2622
+ ```ruby
2623
+ # app.rb
2624
+ require 'sinatra'
2625
+
2626
+ get '/' do
2627
+ 'Hello world!'
2628
+ end
2629
+ ```
2630
+
2631
+ And a corresponding `config.ru`:
2632
+
2633
+ ```ruby
2634
+ require './app'
2635
+ run Sinatra::Application
2636
+ ```
2637
+
2638
+ ### When to use a config.ru?
2639
+
2640
+ A `config.ru` file is recommended if:
2641
+
2642
+ * You want to deploy with a different Rack handler (Passenger, Unicorn,
2643
+ Heroku, ...).
2644
+ * You want to use more than one subclass of `Sinatra::Base`.
2645
+ * You want to use Sinatra only for middleware, and not as an endpoint.
2646
+
2647
+ **There is no need to switch to a `config.ru` simply because you
2648
+ switched to the modular style, and you don't have to use the modular
2649
+ style for running with a `config.ru`.**
2650
+
2651
+ ### Using Sinatra as Middleware
2652
+
2653
+ Not only is Sinatra able to use other Rack middleware, any Sinatra
2654
+ application can, in turn, be added in front of any Rack endpoint as
2655
+ middleware itself. This endpoint could be another Sinatra application,
2656
+ or any other Rack-based application (Rails/Hanami/Roda/...):
2657
+
2658
+ ```ruby
2659
+ require 'sinatra/base'
2660
+
2661
+ class LoginScreen < Sinatra::Base
2662
+ enable :sessions
2663
+
2664
+ get('/login') { haml :login }
2665
+
2666
+ post('/login') do
2667
+ if params['name'] == 'admin' && params['password'] == 'admin'
2668
+ session['user_name'] = params['name']
2669
+ else
2670
+ redirect '/login'
2671
+ end
2672
+ end
2673
+ end
2674
+
2675
+ class MyApp < Sinatra::Base
2676
+ # middleware will run before filters
2677
+ use LoginScreen
2678
+
2679
+ before do
2680
+ unless session['user_name']
2681
+ halt "Access denied, please <a href='/login'>login</a>."
2682
+ end
2683
+ end
2684
+
2685
+ get('/') { "Hello #{session['user_name']}." }
2686
+ end
2687
+ ```
2688
+
2689
+ ### Dynamic Application Creation
2690
+
2691
+ Sometimes you want to create new applications at runtime without having to
2692
+ assign them to a constant. You can do this with `Sinatra.new`:
2693
+
2694
+ ```ruby
2695
+ require 'sinatra/base'
2696
+ my_app = Sinatra.new { get('/') { "hi" } }
2697
+ my_app.run!
2698
+ ```
2699
+
2700
+ It takes the application to inherit from as an optional argument:
2701
+
2702
+ ```ruby
2703
+ # config.ru (run with rackup)
2704
+ require 'sinatra/base'
2705
+
2706
+ controller = Sinatra.new do
2707
+ enable :logging
2708
+ helpers MyHelpers
2709
+ end
2710
+
2711
+ map('/a') do
2712
+ run Sinatra.new(controller) { get('/') { 'a' } }
2713
+ end
2714
+
2715
+ map('/b') do
2716
+ run Sinatra.new(controller) { get('/') { 'b' } }
2717
+ end
2718
+ ```
2719
+
2720
+ This is especially useful for testing Sinatra extensions or using Sinatra in
2721
+ your own library.
2722
+
2723
+ This also makes using Sinatra as middleware extremely easy:
2724
+
2725
+ ```ruby
2726
+ require 'sinatra/base'
2727
+
2728
+ use Sinatra do
2729
+ get('/') { ... }
2730
+ end
2731
+
2732
+ run RailsProject::Application
2733
+ ```
2734
+
2735
+ ## Scopes and Binding
2736
+
2737
+ The scope you are currently in determines what methods and variables are
2738
+ available.
2739
+
2740
+ ### Application/Class Scope
2741
+
2742
+ Every Sinatra application corresponds to a subclass of `Sinatra::Base`.
2743
+ If you are using the top-level DSL (`require 'sinatra'`), then this
2744
+ class is `Sinatra::Application`, otherwise it is the subclass you
2745
+ created explicitly. At the class level, you have methods like `get` or
2746
+ `before`, but you cannot access the `request` or `session` objects, as
2747
+ there is only a single application class for all requests.
2748
+
2749
+ Options created via `set` are methods at class level:
2750
+
2751
+ ```ruby
2752
+ class MyApp < Sinatra::Base
2753
+ # Hey, I'm in the application scope!
2754
+ set :foo, 42
2755
+ foo # => 42
2756
+
2757
+ get '/foo' do
2758
+ # Hey, I'm no longer in the application scope!
2759
+ end
2760
+ end
2761
+ ```
2762
+
2763
+ You have the application scope binding inside:
2764
+
2765
+ * Your application class body
2766
+ * Methods defined by extensions
2767
+ * The block passed to `helpers`
2768
+ * Procs/blocks used as a value for `set`
2769
+ * The block passed to `Sinatra.new`
2770
+
2771
+ You can reach the scope object (the class) like this:
2772
+
2773
+ * Via the object passed to configure blocks (`configure { |c| ... }`)
2774
+ * `settings` from within the request scope
2775
+
2776
+ ### Request/Instance Scope
2777
+
2778
+ For every incoming request, a new instance of your application class is
2779
+ created, and all handler blocks run in that scope. From within this scope you
2780
+ can access the `request` and `session` objects or call rendering methods like
2781
+ `erb` or `haml`. You can access the application scope from within the request
2782
+ scope via the `settings` helper:
2783
+
2784
+ ```ruby
2785
+ class MyApp < Sinatra::Base
2786
+ # Hey, I'm in the application scope!
2787
+ get '/define_route/:name' do
2788
+ # Request scope for '/define_route/:name'
2789
+ @value = 42
2790
+
2791
+ settings.get("/#{params['name']}") do
2792
+ # Request scope for "/#{params['name']}"
2793
+ @value # => nil (not the same request)
2794
+ end
2795
+
2796
+ "Route defined!"
2797
+ end
2798
+ end
2799
+ ```
2800
+
2801
+ You have the request scope binding inside:
2802
+
2803
+ * get, head, post, put, delete, options, patch, link and unlink blocks
2804
+ * before and after filters
2805
+ * helper methods
2806
+ * templates/views
2807
+
2808
+ ### Delegation Scope
2809
+
2810
+ The delegation scope just forwards methods to the class scope. However, it
2811
+ does not behave exactly like the class scope, as you do not have the class
2812
+ binding. Only methods explicitly marked for delegation are available, and you
2813
+ do not share variables/state with the class scope (read: you have a different
2814
+ `self`). You can explicitly add method delegations by calling
2815
+ `Sinatra::Delegator.delegate :method_name`.
2816
+
2817
+ You have the delegate scope binding inside:
2818
+
2819
+ * The top-level binding, if you did `require "sinatra"`
2820
+ * An object extended with the `Sinatra::Delegator` mixin
2821
+
2822
+ Have a look at the code for yourself: here's the
2823
+ [Sinatra::Delegator mixin](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/base.rb#L1609-1633)
2824
+ being [extending the main object](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/main.rb#L28-30).
2825
+
2826
+ ## Command Line
2827
+
2828
+ Sinatra applications can be run directly:
2829
+
2830
+ ```shell
2831
+ ruby myapp.rb [-h] [-x] [-q] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER]
2832
+ ```
2833
+
2834
+ Options are:
2835
+
2836
+ ```
2837
+ -h # help
2838
+ -p # set the port (default is 4567)
2839
+ -o # set the host (default is 0.0.0.0)
2840
+ -e # set the environment (default is development)
2841
+ -s # specify rack server/handler (default is puma)
2842
+ -q # turn on quiet mode for server (default is off)
2843
+ -x # turn on the mutex lock (default is off)
2844
+ ```
2845
+
2846
+ ### Multi-threading
2847
+
2848
+ _Paraphrasing from
2849
+ [this StackOverflow answer](https://stackoverflow.com/a/6282999/5245129)
2850
+ by Konstantin_
2851
+
2852
+ Sinatra doesn't impose any concurrency model but leaves that to the
2853
+ underlying Rack handler (server) like Puma or Falcon. Sinatra
2854
+ itself is thread-safe, so there won't be any problem if the Rack handler
2855
+ uses a threaded model of concurrency.
2856
+
2857
+ ## Requirement
2858
+
2859
+ The following Ruby versions are officially supported:
2860
+ <dl>
2861
+ <dt>Ruby</dt>
2862
+ <dd>
2863
+ <a href="https://www.ruby-lang.org/en/downloads/">The stable releases</a> are fully supported and recommended.
2864
+ </dd>
2865
+
2866
+ <dt>TruffleRuby</dt>
2867
+ <dd>
2868
+ The latest stable release of TruffleRuby is supported.
2869
+ </dd>
2870
+
2871
+ <dt>JRuby</dt>
2872
+ <dd>
2873
+ The latest stable release of JRuby is supported. It is not
2874
+ recommended to use C extensions with JRuby.
2875
+ </dd>
2876
+ </dl>
2877
+
2878
+ Versions of Ruby before 2.7.8 are no longer supported as of Sinatra 4.0.0.
2879
+
2880
+ Sinatra should work on any operating system supported by the chosen Ruby
2881
+ implementation.
2882
+
2883
+ Running Sinatra on a not officially supported Ruby flavor means that if things only break there we assume it's not our issue but theirs.
2884
+
2885
+ ## The Bleeding Edge
2886
+
2887
+ If you would like to use Sinatra's latest bleeding-edge code, feel free
2888
+ to run your application against the main branch, it should be rather
2889
+ stable.
2890
+
2891
+ We also push out prerelease gems from time to time, so you can do a
2892
+
2893
+ ```shell
2894
+ gem install sinatra --pre
2895
+ ```
2896
+
2897
+ to get some of the latest features.
2898
+
2899
+ ### With Bundler
2900
+
2901
+ If you want to run your application with the latest Sinatra, using
2902
+ [Bundler](https://bundler.io) is the recommended way.
2903
+
2904
+ First, install bundler, if you haven't:
2905
+
2906
+ ```shell
2907
+ gem install bundler
2908
+ ```
2909
+
2910
+ Then, in your project directory, create a `Gemfile`:
2911
+
2912
+ ```ruby
2913
+ source 'https://rubygems.org'
2914
+ gem 'sinatra', :github => 'sinatra/sinatra'
2915
+
2916
+ # other dependencies
2917
+ gem 'haml' # for instance, if you use haml
2918
+ ```
2919
+
2920
+ Note that you will have to list all your application's dependencies in
2921
+ the `Gemfile`. Sinatra's direct dependencies (Rack and Tilt) will,
2922
+ however, be automatically fetched and added by Bundler.
2923
+
2924
+ Now you can run your app like this:
2925
+
2926
+ ```shell
2927
+ bundle exec ruby myapp.rb
2928
+ ```
2929
+
2930
+ ## Versioning
2931
+
2932
+ Sinatra follows [Semantic Versioning](https://semver.org/), both SemVer and
2933
+ SemVerTag.
2934
+
2935
+ ## Further Reading
2936
+
2937
+ * [Project Website](https://sinatrarb.com/) - Additional documentation,
2938
+ news, and links to other resources.
2939
+ * [Contributing](https://sinatrarb.com/contributing) - Find a bug? Need
2940
+ help? Have a patch?
2941
+ * [Issue tracker](https://github.com/sinatra/sinatra/issues)
2942
+ * [Twitter](https://twitter.com/sinatra)
2943
+ * [Mailing List](https://groups.google.com/forum/#!forum/sinatrarb)
2944
+ * IRC: [#sinatra](irc://chat.freenode.net/#sinatra) on [Freenode](https://freenode.net)
2945
+ * [Sinatra & Friends](https://discord.gg/ncjsfsNHh7) on Discord
2946
+ * [Sinatra Book](https://github.com/sinatra/sinatra-book) - Cookbook Tutorial
2947
+ * [Sinatra Recipes](http://recipes.sinatrarb.com/) - Community contributed
2948
+ recipes
2949
+ * API documentation for the [latest release](https://www.rubydoc.info/gems/sinatra)
2950
+ or the [current HEAD](https://www.rubydoc.info/github/sinatra/sinatra) on
2951
+ [RubyDoc](https://www.rubydoc.info/)
2952
+ * [CI Actions](https://github.com/sinatra/sinatra/actions)