Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 1025 lines (705 sloc) 26.351 kb
df800b5 Docs are started
Blake Mizerany authored
1 = Sinatra
2
4c91e54 Tom Hartwell Web applications should not be hyphenated
watchdogtimer authored
3 Sinatra is a DSL for quickly creating web applications in Ruby with minimal
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
4 effort:
df800b5 Docs are started
Blake Mizerany authored
5
6 # myapp.rb
7 require 'sinatra'
c37db5c Konstantin Haase minor adjustments and fixes for the readme examples
rkh authored
8
df800b5 Docs are started
Blake Mizerany authored
9 get '/' do
10 'Hello world!'
11 end
12
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
13 Install the gem and run with:
df800b5 Docs are started
Blake Mizerany authored
14
8465d49 Konstantin Haase Avoid `require "rubygems"` and `sudo` in README.
rkh authored
15 gem install sinatra
16 ruby -rubygems myapp.rb
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
17
18 View at: http://localhost:4567
19
20 == Routes
21
22 In Sinatra, a route is an HTTP method paired with an URL matching pattern.
23 Each route is associated with a block:
df800b5 Docs are started
Blake Mizerany authored
24
25 get '/' do
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
26 .. show something ..
df800b5 Docs are started
Blake Mizerany authored
27 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
28
df800b5 Docs are started
Blake Mizerany authored
29 post '/' do
30 .. create something ..
31 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
32
df800b5 Docs are started
Blake Mizerany authored
33 put '/' do
34 .. update something ..
35 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
36
df800b5 Docs are started
Blake Mizerany authored
37 delete '/' do
38 .. annihilate something ..
39 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
40
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
41 Routes are matched in the order they are defined. The first route that
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
42 matches the request is invoked.
1776a80 Added Version and Docs
Blake Mizerany authored
43
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
44 Route patterns may include named parameters, accessible via the
45 <tt>params</tt> hash:
1776a80 Added Version and Docs
Blake Mizerany authored
46
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
47 get '/hello/:name' do
ce0fe87 Scott Johnson fix inaccurate comment in README
scottj97 authored
48 # matches "GET /hello/foo" and "GET /hello/bar"
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
49 # params[:name] is 'foo' or 'bar'
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
50 "Hello #{params[:name]}!"
1776a80 Added Version and Docs
Blake Mizerany authored
51 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
52
6569d1b Brandon Dimcheff Added route block params in routing statements [#140]
bdimcheff authored
53 You can also access named parameters via block parameters:
54
55 get '/hello/:name' do |n|
56 "Hello #{n}!"
57 end
58
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
59 Route patterns may also include splat (or wildcard) parameters, accessible
60 via the <tt>params[:splat]</tt> array.
1776a80 Added Version and Docs
Blake Mizerany authored
61
9c85e99 Victor Hugo Borja Specs, documentation and fixes for splat'n routes
vic authored
62 get '/say/*/to/*' do
63 # matches /say/hello/to/world
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
64 params[:splat] # => ["hello", "world"]
9c85e99 Victor Hugo Borja Specs, documentation and fixes for splat'n routes
vic authored
65 end
66
67 get '/download/*.*' do
68 # matches /download/path/to/file.xml
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
69 params[:splat] # => ["path/to/file", "xml"]
1776a80 Added Version and Docs
Blake Mizerany authored
70 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
71
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
72 Route matching with Regular Expressions:
73
74 get %r{/hello/([\w]+)} do
75 "Hello, #{params[:captures].first}!"
76 end
77
6569d1b Brandon Dimcheff Added route block params in routing statements [#140]
bdimcheff authored
78 Or with a block parameter:
79
80 get %r{/hello/([\w]+)} do |c|
81 "Hello, #{c}!"
82 end
83
726feeb Konstantin Haase Documentation for condition. Fixes GH #15.
rkh authored
84 === Conditions
85
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
86 Routes may include a variety of matching conditions, such as the user agent:
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
87
1776a80 Added Version and Docs
Blake Mizerany authored
88 get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
89 "You're using Songbird version #{params[:agent][0]}"
90 end
91
92 get '/foo' do
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
93 # Matches non-songbird browsers
1776a80 Added Version and Docs
Blake Mizerany authored
94 end
df800b5 Docs are started
Blake Mizerany authored
95
fa52709 Konstantin Haase fix markup for inline code in README
rkh authored
96 Other available conditions are +host_name+ and +provides+:
726feeb Konstantin Haase Documentation for condition. Fixes GH #15.
rkh authored
97
98 get '/', :host_name => /^admin\./ do
99 "Admin Area, Access denied!"
100 end
101
102 get '/', :provides => 'html' do
103 haml :index
104 end
105
106 get '/', :provides => ['rss', 'atom', 'xml'] do
107 builder :feed
108 end
109
110 You can easily define your own conditions:
111
112 set(:probability) { |value| condition { rand <= value } }
113
114 get '/win_a_car', :probability => 0.1 do
115 "You won!"
116 end
117
118 get '/win_a_car' do
119 "Sorry, you lost."
120 end
121
aaeb564 Konstantin Haase document route return values, fixes GH #23
rkh authored
122 === Return values
123
124 The return value of a route block determines at least the response body passed
125 on to the HTTP client, or at least the next middleware in the Rack stack.
126 Most commonly this is a string, as in the above examples. But other values are
127 also accepted.
128
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
129 You can return any object that would either be a valid Rack response, Rack
130 body object or HTTP status code:
aaeb564 Konstantin Haase document route return values, fixes GH #23
rkh authored
131
626f689 Konstantin Haase fix markup for multi word inline code in README
rkh authored
132 * An Array with three elements: <tt>[status (Fixnum), headers (Hash), response body (responds to #each)]</tt>
133 * An Array with two elements: <tt>[status (Fixnum), response body (responds to #each)]</tt>
9c73cf7 Konstantin Haase fix markup for multi word inline code in README, take two (apparently # ...
rkh authored
134 * An object that responds to <tt>#each</tt> and passes nothing but strings to the given block
aaeb564 Konstantin Haase document route return values, fixes GH #23
rkh authored
135 * A Fixnum representing the status code
136
137 That way we can for instance easily implement a streaming example:
138
139 class Stream
140 def each
141 100.times { |i| yield "#{i}\n" }
142 end
143 end
144
8fbd9c2 Konstantin Haase Simplify streaming example.
rkh authored
145 get('/') { Stream.new }
aaeb564 Konstantin Haase document route return values, fixes GH #23
rkh authored
146
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
147 == Static Files
047edc6 update README with Static help
Blake Mizerany authored
148
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
149 Static files are served from the <tt>./public</tt> directory. You can specify
150 a different location by setting the <tt>:public</tt> option:
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
151
152 set :public, File.dirname(__FILE__) + '/static'
df800b5 Docs are started
Blake Mizerany authored
153
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
154 Note that the public directory name is not included in the URL. A file
85b4462 Ryan Tomayko README: fix formatting on static file note
rtomayko authored
155 <tt>./public/css/style.css</tt> is made available as
156 <tt>http://example.com/css/style.css</tt>.
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
157
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
158 == Views / Templates
df800b5 Docs are started
Blake Mizerany authored
159
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
160 Templates are assumed to be located directly under the <tt>./views</tt>
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
161 directory. To use a different views directory:
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
162
163 set :views, File.dirname(__FILE__) + '/templates'
164
06161bf Markus Prinz Note on passing template symbols vs. strings in README
cypher authored
165 One important thing to remember is that you always have to reference
166 templates with symbols, even if they're in a subdirectory (in this
1255737 Michel Added a transition to better explain that templates must be defined with...
michelc authored
167 case use <tt>:'subdir/template'</tt>). You must use a symbol because
168 otherwise rendering methods will render any strings passed to them
169 directly.
06161bf Markus Prinz Note on passing template symbols vs. strings in README
cypher authored
170
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
171 === Haml Templates
df800b5 Docs are started
Blake Mizerany authored
172
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
173 The haml gem/library is required to render HAML templates:
174
801163e Blake Mizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
175 ## You'll need to require haml in your app
176 require 'haml'
177
df800b5 Docs are started
Blake Mizerany authored
178 get '/' do
179 haml :index
180 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
181
182 Renders <tt>./views/index.haml</tt>.
183
0321ada Doug Ireton In README docs, fix links to HAML and SASS Options pages.
dougireton authored
184 {Haml's options}[http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html#options]
d359dc9 Kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
185 can be set globally through Sinatra's configurations,
186 see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
187 and overridden on an individual basis.
188
c37db5c Konstantin Haase minor adjustments and fixes for the readme examples
rkh authored
189 set :haml, :format => :html5 # default Haml format is :xhtml
d359dc9 Kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
190
191 get '/' do
c37db5c Konstantin Haase minor adjustments and fixes for the readme examples
rkh authored
192 haml :index, :format => :html4 # overridden
d359dc9 Kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
193 end
194
195
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
196 === Erb Templates
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
197
801163e Blake Mizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
198 ## You'll need to require erb in your app
199 require 'erb'
200
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
201 get '/' do
202 erb :index
203 end
204
205 Renders <tt>./views/index.erb</tt>
206
7c5d693 Simon Rozet Doc for erubis
sr authored
207 === Erubis
208
84f2e0c Jason Stewart Correction to erubis template rendering instructions
jstewart authored
209 The erubis gem/library is required to render erubis templates:
7c5d693 Simon Rozet Doc for erubis
sr authored
210
211 ## You'll need to require erubis in your app
212 require 'erubis'
213
214 get '/' do
215 erubis :index
216 end
217
218 Renders <tt>./views/index.erubis</tt>
219
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
220 === Builder Templates
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
221
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
222 The builder gem/library is required to render builder templates:
df800b5 Docs are started
Blake Mizerany authored
223
801163e Blake Mizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
224 ## You'll need to require builder in your app
225 require 'builder'
226
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
227 get '/' do
228 builder :index
229 end
230
231 Renders <tt>./views/index.builder</tt>.
232
dd81da1 Konstantin Haase Add nokogiri helper method. Tilt supports Nokogiri for quite some time n...
rkh authored
233 === Nokogiri Templates
234
235 The nokogiri gem/library is required to render nokogiri templates:
236
237 ## You'll need to require nokogiri in your app
238 require 'nokogiri'
239
240 get '/' do
241 nokogiri :index
242 end
243
244 Renders <tt>./views/index.nokogiri</tt>.
245
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
246 === Sass Templates
247
248 The sass gem/library is required to render Sass templates:
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
249
801163e Blake Mizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
250 ## You'll need to require haml or sass in your app
251 require 'sass'
252
4144ac1 Nickolas Means Added Sass information to documentation.
nmeans authored
253 get '/stylesheet.css' do
254 sass :stylesheet
255 end
256
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
257 Renders <tt>./views/stylesheet.sass</tt>.
258
0321ada Doug Ireton In README docs, fix links to HAML and SASS Options pages.
dougireton authored
259 {Sass' options}[http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#options]
d359dc9 Kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
260 can be set globally through Sinatra's configurations,
261 see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
262 and overridden on an individual basis.
263
c37db5c Konstantin Haase minor adjustments and fixes for the readme examples
rkh authored
264 set :sass, :style => :compact # default Sass style is :nested
d359dc9 Kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
265
266 get '/stylesheet.css' do
b90d00c Simon Rozet Update sass example re. options
sr authored
267 sass :stylesheet, :style => :expanded # overridden
d359dc9 Kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
268 end
269
cf3c218 Pedro Menezes Adding scss support through specific command
pedromenezes authored
270 === Scss Templates
271
272 The sass gem/library is required to render Scss templates:
273
274 ## You'll need to require haml or sass in your app
275 require 'sass'
276
277 get '/stylesheet.css' do
278 scss :stylesheet
279 end
280
281 Renders <tt>./views/stylesheet.scss</tt>.
282
283 {Scss' options}[http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#options]
284 can be set globally through Sinatra's configurations,
285 see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
286 and overridden on an individual basis.
287
c37db5c Konstantin Haase minor adjustments and fixes for the readme examples
rkh authored
288 set :scss, :style => :compact # default Scss style is :nested
cf3c218 Pedro Menezes Adding scss support through specific command
pedromenezes authored
289
290 get '/stylesheet.css' do
291 scss :stylesheet, :style => :expanded # overridden
292 end
293
621bfcb Andriy Savchenko Added Less support
Ptico authored
294 === Less Templates
295
296 The less gem/library is required to render Less templates:
297
298 ## You'll need to require less in your app
299 require 'less'
300
301 get '/stylesheet.css' do
302 less :stylesheet
303 end
304
305 Renders <tt>./views/stylesheet.less</tt>.
306
28a3a35 Konstantin Haase Add liquid helper method. Tilt supports liquid for quite some time now, ...
rkh authored
307 === Liquid Templates
308
309 The liquid gem/library is required to render Liquid templates:
310
311 ## You'll need to require liquid in your app
312 require 'liquid'
313
314 get '/' do
315 liquid :index
316 end
317
318 Renders <tt>./views/index.liquid</tt>.
319
320 Since you cannot call Ruby methods (except for +yield+) from a Liquid
321 template, you almost always want to pass locals to it:
322
323 liquid :index, :locals => { :key => 'value' }
324
970169b Konstantin Haase Add markdown helper method. Tilt supports markdown for quite some time n...
rkh authored
325 === Markdown Templates
326
327 The rdiscount gem/library is required to render Markdown templates:
328
329 ## You'll need to require rdiscount in your app
330 require "rdiscount"
331
332 get '/' do
333 markdown :index
334 end
335
336 Renders <tt>./views/index.markdown</tt> (+md+ and +mkd+ are also valid file
337 extensions).
338
339 It is not possible to call methods from markdown, nor to pass locals to it. You therefore will usually use it in combination with another rendering engine:
340
341 erb :overview, :locals => { :text => markdown(:introduction) }
342
343 Note that you may also call the markdown method from within other templates:
344
345 %h1 Hello From Haml!
346 %p= markdown(:greetings)
347
b464e02 Konstantin Haase Add textile helper method. Tilt supports textile for quite some time now...
rkh authored
348 === Textile Templates
349
350 The RedCloth gem/library is required to render Textile templates:
351
64488d5 Gabriel Andretta fixes a few copy/paste errors in the README
gnandretta authored
352 ## You'll need to require redcloth in your app
b464e02 Konstantin Haase Add textile helper method. Tilt supports textile for quite some time now...
rkh authored
353 require "redcloth"
354
355 get '/' do
356 textile :index
357 end
358
359 Renders <tt>./views/index.textile</tt>.
360
361 It is not possible to call methods from textile, nor to pass locals to it. You therefore will usually use it in combination with another rendering engine:
362
363 erb :overview, :locals => { :text => textile(:introduction) }
364
365 Note that you may also call the textile method from within other templates:
366
367 %h1 Hello From Haml!
368 %p= textile(:greetings)
369
c248dba Konstantin Haase Add rdoc helper method. Tilt supports RDoc for quite some time now, but ...
rkh authored
370 === RDoc Templates
371
372 The RDoc gem/library is required to render RDoc templates:
373
64488d5 Gabriel Andretta fixes a few copy/paste errors in the README
gnandretta authored
374 ## You'll need to require rdoc in your app
c248dba Konstantin Haase Add rdoc helper method. Tilt supports RDoc for quite some time now, but ...
rkh authored
375 require "rdoc"
376
377 get '/' do
378 rdoc :index
379 end
380
381 Renders <tt>./views/index.rdoc</tt>.
382
383 It is not possible to call methods from rdoc, nor to pass locals to it. You therefore will usually use it in combination with another rendering engine:
384
385 erb :overview, :locals => { :text => rdoc(:introduction) }
386
387 Note that you may also call the rdoc method from within other templates:
388
389 %h1 Hello From Haml!
390 %p= rdoc(:greetings)
391
7cb94f2 Konstantin Haase Add radius helper method. Tilt supports radius for quite some time now, ...
rkh authored
392 === Radius Templates
393
394 The radius gem/library is required to render Radius templates:
395
396 ## You'll need to require radius in your app
397 require 'radius'
398
399 get '/' do
400 radius :index
401 end
402
403 Renders <tt>./views/index.radius</tt>.
404
405 Since you cannot call Ruby methods (except for +yield+) from a Radius
406 template, you almost always want to pass locals to it:
407
408 radius :index, :locals => { :key => 'value' }
409
8ce74b3 Konstantin Haase Add markaby helper method. Tilt supports Markaby for quite some time now...
rkh authored
410 === Markaby Templates
411
412 The markaby gem/library is required to render Markaby templates:
413
414 ## You'll need to require markaby in your app
415 require 'markaby'
416
417 get '/' do
418 markaby :index
419 end
420
421 Renders <tt>./views/index.mab</tt>.
422
f58d015 Konstantin Haase Add coffee helper method. Tilt supports CoffeeScript again, but it was n...
rkh authored
423 === CoffeeScript Templates
424
425 The coffee-script gem/library and the `coffee` binary are required to render
426 CoffeeScript templates:
427
428 ## You'll need to require coffee-script in your app
429 require 'coffee-script'
430
431 get '/application.js' do
432 coffee :application
433 end
434
435 Renders <tt>./views/application.coffee</tt>.
436
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
437 === Inline Templates
df800b5 Docs are started
Blake Mizerany authored
438
439 get '/' do
440 haml '%div.title Hello World'
441 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
442
443 Renders the inlined template string.
df800b5 Docs are started
Blake Mizerany authored
444
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
445 === Accessing Variables in Templates
df800b5 Docs are started
Blake Mizerany authored
446
5018264 Ryan Tomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
447 Templates are evaluated within the same context as route handlers. Instance
448 variables set in route handlers are direcly accessible by templates:
df800b5 Docs are started
Blake Mizerany authored
449
450 get '/:id' do
451 @foo = Foo.find(params[:id])
95aca76 Ben Bleything fix documentation of variable interpolation into templates
bleything authored
452 haml '%h1= @foo.name'
df800b5 Docs are started
Blake Mizerany authored
453 end
454
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
455 Or, specify an explicit Hash of local variables:
df800b5 Docs are started
Blake Mizerany authored
456
457 get '/:id' do
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
458 foo = Foo.find(params[:id])
95aca76 Ben Bleything fix documentation of variable interpolation into templates
bleything authored
459 haml '%h1= foo.name', :locals => { :foo => foo }
df800b5 Docs are started
Blake Mizerany authored
460 end
461
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
462 This is typically used when rendering templates as partials from within
463 other templates.
464
3ef8eed Simon Rozet Deprecate use_in_file_templates!
sr authored
465 === Inline Templates
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
466
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
467 Templates may be defined at the end of the source file:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
468
eec7d21 Blake Mizerany In-file-templates are automaticly loaded for you.
bmizerany authored
469 require 'sinatra'
470
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
471 get '/' do
472 haml :index
473 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
474
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
475 __END__
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
476
f71330e Blake Mizerany quick doc fix
bmizerany authored
477 @@ layout
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
478 %html
479 = yield
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
480
f71330e Blake Mizerany quick doc fix
bmizerany authored
481 @@ index
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
482 %div.title Hello world!!!!!
483
6584711 Konstantin Haase Minor markup fix in README.
rkh authored
484 NOTE: Inline templates defined in the source file that requires sinatra are
485 automatically loaded. Call <tt>enable :inline_templates<tt> explicitly if you
3ef8eed Simon Rozet Deprecate use_in_file_templates!
sr authored
486 have inline templates in other source files.
eec7d21 Blake Mizerany In-file-templates are automaticly loaded for you.
bmizerany authored
487
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
488 === Named Templates
489
5018264 Ryan Tomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
490 Templates may also be defined using the top-level <tt>template</tt> method:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
491
492 template :layout do
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
493 "%html\n =yield\n"
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
494 end
495
496 template :index do
497 '%div.title Hello World!'
498 end
499
500 get '/' do
501 haml :index
502 end
503
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
504 If a template named "layout" exists, it will be used each time a template
505 is rendered. You can disable layouts by passing <tt>:layout => false</tt>.
578bbab Damian Janowski Updating README for :layout => true.
djanowski authored
506
507 get '/' do
508 haml :index, :layout => !request.xhr?
509 end
510
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
511 == Helpers
df800b5 Docs are started
Blake Mizerany authored
512
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
513 Use the top-level <tt>helpers</tt> method to define helper methods for use in
5018264 Ryan Tomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
514 route handlers and templates:
df800b5 Docs are started
Blake Mizerany authored
515
516 helpers do
517 def bar(name)
518 "#{name}bar"
519 end
520 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
521
1776a80 Added Version and Docs
Blake Mizerany authored
522 get '/:name' do
523 bar(params[:name])
524 end
df800b5 Docs are started
Blake Mizerany authored
525
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
526 == Filters
df800b5 Docs are started
Blake Mizerany authored
527
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
528 Before filters are evaluated before each request within the same context as
529 the routes will be and can modify the request and response. Instance variables
530 set in filters are accessible by routes and templates:
1776a80 Added Version and Docs
Blake Mizerany authored
531
df800b5 Docs are started
Blake Mizerany authored
532 before do
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
533 @note = 'Hi!'
534 request.path_info = '/foo/bar/baz'
535 end
536
537 get '/foo/*' do
538 @note #=> 'Hi!'
539 params[:splat] #=> 'bar/baz'
df800b5 Docs are started
Blake Mizerany authored
540 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
541
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
542 After filter are evaluated after each request within the same context and can
543 also modify the request and response. Instance variables set in before filters
544 and routes are accessible by after filters:
4e50ddb Jimmy Schementi Adds after filters
jschementi authored
545
546 after do
547 puts response.status
548 end
549
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
550 Filters optionally taking a pattern, causing them to be evaluated only if the
551 request path matches that pattern:
da047d3 Konstantin Haase add pattern matching to before/after filters.
rkh authored
552
553 before '/protected/*' do
554 authenticate!
555 end
556
557 after '/create/:slug' do |slug|
558 session[:last_slug] = slug
559 end
560
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
561 == Halting
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
562
4e50ddb Jimmy Schementi Adds after filters
jschementi authored
563 To immediately stop a request within a filter or route use:
df800b5 Docs are started
Blake Mizerany authored
564
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
565 halt
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
566
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
567 You can also specify the status when halting:
fbbd822 Simon Rozet More 'halt' doc
sr authored
568
569 halt 410
570
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
571 Or the body:
df800b5 Docs are started
Blake Mizerany authored
572
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
573 halt 'this will be the body'
df800b5 Docs are started
Blake Mizerany authored
574
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
575 Or both:
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
576
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
577 halt 401, 'go away!'
df800b5 Docs are started
Blake Mizerany authored
578
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
579 With headers:
fbbd822 Simon Rozet More 'halt' doc
sr authored
580
581 halt 402, {'Content-Type' => 'text/plain'}, 'revenge'
582
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
583 == Passing
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
584
5018264 Ryan Tomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
585 A route can punt processing to the next matching route using <tt>pass</tt>:
df800b5 Docs are started
Blake Mizerany authored
586
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
587 get '/guess/:who' do
588 pass unless params[:who] == 'Frank'
6c9488e Simon Rozet Stick to single quote; kill a blank line
sr authored
589 'You got me!'
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
590 end
591
592 get '/guess/*' do
6c9488e Simon Rozet Stick to single quote; kill a blank line
sr authored
593 'You missed!'
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
594 end
595
596 The route block is immediately exited and control continues with the next
597 matching route. If no matching route is found, a 404 is returned.
df800b5 Docs are started
Blake Mizerany authored
598
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
599 == Accessing the Request Object
600
3297a61 Fix typo in README.
Lee Jarvis authored
601 The incoming request object can be accessed from request level (filter, routes, error handlers) through the `request` method:
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
602
603 # app running on http://example.com/example
604 get '/foo' do
605 request.body # request body sent by the client (see below)
606 request.scheme # "http"
607 request.script_name # "/example"
608 request.path_info # "/foo"
609 request.port # 80
610 request.request_method # "GET"
611 request.query_string # ""
612 request.content_length # length of request.body
613 request.media_type # media type of request.body
614 request.host # "example.com"
615 request.get? # true (similar methods for other verbs)
616 request.form_data? # false
617 request["SOME_HEADER"] # value of SOME_HEADER header
618 request.referer # the referer of the client or '/'
619 request.user_agent # user agent (used by :agent condition)
620 request.cookies # hash of browser cookies
621 request.xhr? # is this an ajax request?
622 request.url # "http://example.com/example/foo"
623 request.path # "/example/foo"
624 request.ip # client IP address
625 request.secure? # false
626 requuest.env # raw env hash handed in by Rack
627 end
628
1fd52d1 Konstantin Haase Fix markup
rkh authored
629 Some options, like <tt>script_name</tt> or <tt>path_info</tt> can also be
630 written:
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
631
632 before { request.path_info = "/" }
633
634 get "/" do
635 "all requests end up here"
636 end
637
638 The <tt>request.body</tt> is an IO or StringIO object:
639
640 post "/api" do
641 request.body.rewind # in case someone already read it
642 data = JSON.parse request.body.read
643 "Hello #{data['name']}!"
644 end
645
13fc79d Ryan Tomayko Remove support for source file reloading [#166]
rtomayko authored
646 == Configuration
1776a80 Added Version and Docs
Blake Mizerany authored
647
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
648 Run once, at startup, in any environment:
1776a80 Added Version and Docs
Blake Mizerany authored
649
650 configure do
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
651 ...
1776a80 Added Version and Docs
Blake Mizerany authored
652 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
653
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
654 Run only when the environment (RACK_ENV environment variable) is set to
13fc79d Ryan Tomayko Remove support for source file reloading [#166]
rtomayko authored
655 <tt>:production</tt>:
1776a80 Added Version and Docs
Blake Mizerany authored
656
657 configure :production do
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
658 ...
1776a80 Added Version and Docs
Blake Mizerany authored
659 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
660
13fc79d Ryan Tomayko Remove support for source file reloading [#166]
rtomayko authored
661 Run when the environment is set to either <tt>:production</tt> or
662 <tt>:test</tt>:
1776a80 Added Version and Docs
Blake Mizerany authored
663
664 configure :production, :test do
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
665 ...
1776a80 Added Version and Docs
Blake Mizerany authored
666 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
667
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
668 == Error handling
1776a80 Added Version and Docs
Blake Mizerany authored
669
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
670 Error handlers run within the same context as routes and before filters, which
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
671 means you get all the goodies it has to offer, like <tt>haml</tt>,
672 <tt>erb</tt>, <tt>halt</tt>, etc.
1776a80 Added Version and Docs
Blake Mizerany authored
673
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
674 === Not Found
1776a80 Added Version and Docs
Blake Mizerany authored
675
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
676 When a <tt>Sinatra::NotFound</tt> exception is raised, or the response's status
677 code is 404, the <tt>not_found</tt> handler is invoked:
1776a80 Added Version and Docs
Blake Mizerany authored
678
679 not_found do
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
680 'This is nowhere to be found.'
1776a80 Added Version and Docs
Blake Mizerany authored
681 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
682
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
683 === Error
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
684
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
685 The +error+ handler is invoked any time an exception is raised from a route
63fd773 Simon Rozet Small doc fix re. after filter
sr authored
686 block or a filter. The exception object can be obtained from the
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
687 <tt>sinatra.error</tt> Rack variable:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
688
1776a80 Added Version and Docs
Blake Mizerany authored
689 error do
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
690 'Sorry there was a nasty error - ' + env['sinatra.error'].name
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
691 end
692
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
693 Custom errors:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
694
695 error MyCustomError do
e7e0e55 Ryan Tomayko Minor docfixes in README.rdoc
rtomayko authored
696 'So what happened was...' + request.env['sinatra.error'].message
1776a80 Added Version and Docs
Blake Mizerany authored
697 end
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
698
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
699 Then, if this happens:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
700
701 get '/' do
702 raise MyCustomError, 'something bad'
703 end
704
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
705 You get this:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
706
707 So what happened was... something bad
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
708
59e797e Simon Rozet Doc for error(500) { }
sr authored
709 Alternatively, you can install error handler for a status code:
710
711 error 403 do
712 'Access forbidden'
713 end
714
715 get '/secret' do
716 403
717 end
718
719 Or a range:
720
721 error 400..510 do
722 'Boom'
723 end
724
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
725 Sinatra installs special <tt>not_found</tt> and <tt>error</tt> handlers when
726 running under the development environment.
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
727
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
728 == Mime types
729
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
730 When using <tt>send_file</tt> or static files you may have mime types Sinatra
6d8b333 Simon Rozet Update README re. mime_type
sr authored
731 doesn't understand. Use +mime_type+ to register them by file extension:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
732
6d8b333 Simon Rozet Update README re. mime_type
sr authored
733 mime_type :foo, 'text/foo'
1776a80 Added Version and Docs
Blake Mizerany authored
734
cb8fcb6 Simon Rozet Doc for content_type :foo
sr authored
735 You can also use it with the +content_type+ helper:
736
737 content_type :foo
738
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
739 == Rack Middleware
bda21f1 Ryan Tomayko add doc on using Rack middleware to README
rtomayko authored
740
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
741 Sinatra rides on Rack[http://rack.rubyforge.org/], a minimal standard
742 interface for Ruby web frameworks. One of Rack's most interesting capabilities
743 for application developers is support for "middleware" -- components that sit
744 between the server and your application monitoring and/or manipulating the
745 HTTP request/response to provide various types of common functionality.
bda21f1 Ryan Tomayko add doc on using Rack middleware to README
rtomayko authored
746
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
747 Sinatra makes building Rack middleware pipelines a cinch via a top-level
748 +use+ method:
bda21f1 Ryan Tomayko add doc on using Rack middleware to README
rtomayko authored
749
750 require 'sinatra'
751 require 'my_custom_middleware'
752
753 use Rack::Lint
754 use MyCustomMiddleware
755
756 get '/hello' do
757 'Hello World'
758 end
759
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
760 The semantics of +use+ are identical to those defined for the
761 Rack::Builder[http://rack.rubyforge.org/doc/classes/Rack/Builder.html] DSL
762 (most frequently used from rackup files). For example, the +use+ method
763 accepts multiple/variable args as well as blocks:
bda21f1 Ryan Tomayko add doc on using Rack middleware to README
rtomayko authored
764
765 use Rack::Auth::Basic do |username, password|
766 username == 'admin' && password == 'secret'
767 end
768
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
769 Rack is distributed with a variety of standard middleware for logging,
770 debugging, URL routing, authentication, and session handling. Sinatra uses
771 many of of these components automatically based on configuration so you
772 typically don't have to +use+ them explicitly.
bda21f1 Ryan Tomayko add doc on using Rack middleware to README
rtomayko authored
773
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
774 == Testing
1776a80 Added Version and Docs
Blake Mizerany authored
775
c831278 Ryan Tomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
776 Sinatra tests can be written using any Rack-based testing library
777 or framework. {Rack::Test}[http://gitrdoc.com/brynary/rack-test] is
778 recommended:
c00a25e Ryan Tomayko Test framework refactoring
rtomayko authored
779
7cfe04a Jon Crosby Fix for test/unit and test/spec docs
jcrosby authored
780 require 'my_sinatra_app'
c3f167f Eric Marden MOD: docs for testing forgot to require test/unit
xentek authored
781 require 'test/unit'
c831278 Ryan Tomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
782 require 'rack/test'
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
783
1776a80 Added Version and Docs
Blake Mizerany authored
784 class MyAppTest < Test::Unit::TestCase
c831278 Ryan Tomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
785 include Rack::Test::Methods
786
787 def app
788 Sinatra::Application
789 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
790
2f377e2 Ryan Tomayko Trim down Testing section in the README; link to doc site instead
rtomayko authored
791 def test_my_default
c00a25e Ryan Tomayko Test framework refactoring
rtomayko authored
792 get '/'
c831278 Ryan Tomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
793 assert_equal 'Hello World!', last_response.body
1776a80 Added Version and Docs
Blake Mizerany authored
794 end
10c90d5 Simon Rozet document testing with rspec
sr authored
795
2f377e2 Ryan Tomayko Trim down Testing section in the README; link to doc site instead
rtomayko authored
796 def test_with_params
c831278 Ryan Tomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
797 get '/meet', :name => 'Frank'
798 assert_equal 'Hello Frank!', last_response.body
10c90d5 Simon Rozet document testing with rspec
sr authored
799 end
800
2f377e2 Ryan Tomayko Trim down Testing section in the README; link to doc site instead
rtomayko authored
801 def test_with_rack_env
c831278 Ryan Tomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
802 get '/', {}, 'HTTP_USER_AGENT' => 'Songbird'
803 assert_equal "You're using Songbird!", last_response.body
1fb5b99 Dylan Egan Bacon support
dylanegan authored
804 end
805 end
806
c831278 Ryan Tomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
807 NOTE: The built-in Sinatra::Test module and Sinatra::TestHarness class
808 are deprecated as of the 0.9.2 release.
1776a80 Added Version and Docs
Blake Mizerany authored
809
5360333 Simon Rozet Add a note about Sinatra::Base to the README
sr authored
810 == Sinatra::Base - Middleware, Libraries, and Modular Apps
811
812 Defining your app at the top-level works well for micro-apps but has
69791f7 Konstantin Haase Minor README adjustments.
rkh authored
813 considerable drawbacks when building reusable components such as Rack
5360333 Simon Rozet Add a note about Sinatra::Base to the README
sr authored
814 middleware, Rails metal, simple libraries with a server component, or
815 even Sinatra extensions. The top-level DSL pollutes the Object namespace
816 and assumes a micro-app style configuration (e.g., a single application
817 file, ./public and ./views directories, logging, exception detail page,
818 etc.). That's where Sinatra::Base comes into play:
819
820 require 'sinatra/base'
821
822 class MyApp < Sinatra::Base
823 set :sessions, true
824 set :foo, 'bar'
825
826 get '/' do
827 'Hello world!'
828 end
829 end
830
831 The MyApp class is an independent Rack component that can act as
832 Rack middleware, a Rack application, or Rails metal. You can +use+ or
833 +run+ this class from a rackup +config.ru+ file; or, control a server
834 component shipped as a library:
835
836 MyApp.run! :host => 'localhost', :port => 9090
837
838 The methods available to Sinatra::Base subclasses are exactly as those
839 available via the top-level DSL. Most top-level apps can be converted to
840 Sinatra::Base components with two modifications:
841
842 * Your file should require +sinatra/base+ instead of +sinatra+;
843 otherwise, all of Sinatra's DSL methods are imported into the main
844 namespace.
845 * Put your app's routes, error handlers, filters, and options in a subclass
846 of Sinatra::Base.
847
848 +Sinatra::Base+ is a blank slate. Most options are disabled by default,
849 including the built-in server. See {Options and Configuration}[http://sinatra.github.com/configuration.html]
850 for details on available options and their behavior.
851
69791f7 Konstantin Haase Minor README adjustments.
rkh authored
852 === Using Sinatra as Middleware
5e8d501 Konstantin Haase Added "Using Sinatra as middleware" section, fixes GH #19.
rkh authored
853
854 Not only is Sinatra able to use other Rack middleware, any Sinatra application
855 can in turn be added in front of any Rack endpoint as middleware itself. This
856 endpoint could be another Sinatra application, or any other Rack-based
857 application (Rails/Ramaze/Camping/...).
858
859 require 'sinatra/base'
860
861 class LoginScreen < Sinatra::Base
862 enable :session
863
864 get('/login') { haml :login }
865
866 post('/login') do
867 if params[:name] = 'admin' and params[:password] = 'admin'
868 session['user_name'] = params[:name]
869 else
870 redirect '/login'
871 end
872 end
873 end
874
875 class MyApp < Sinatra::Base
876 # middleware will run before filters
877 use LoginScreen
878
879 before do
880 unless session['user_name']
881 halt "Access denied, please <a href='/login'>login</a>."
882 end
883 end
884
885 get('/') { "Hello #{session['user_name']}." }
886 end
887
3f21c3f Konstantin Haase Document different scopes/bindings.
rkh authored
888 == Scopes and Binding
889
6233ce4 Konstantin Haase Proof-reading Scopes section
rkh authored
890 The scope you are currently in determines what methods and variables are
891 available.
3f21c3f Konstantin Haase Document different scopes/bindings.
rkh authored
892
893 === Application/Class Scope
894
895 Every Sinatra application corresponds to a subclass of Sinatra::Base. If you
896 are using the top level DSL (<tt>require 'sinatra'</tt>), then this class is
897 Sinatra::Application, otherwise it is the subclass you created explicitly. At
898 class level you have methods like `get` or `before`, but you cannot access the
899 `request` object or the `session`, as there only is a single application class
900 for all requests.
901
902 Options created via `set` are methods at class level:
903
904 class MyApp << Sinatra::Base
905 # Hey, I'm in the application scope!
906 set :foo, 42
907 foo # => 42
908
909 get '/foo' do
910 # Hey, I'm no longer in the application scope!
911 end
912 end
913
6233ce4 Konstantin Haase Proof-reading Scopes section
rkh authored
914 You have the application scope binding inside:
3f21c3f Konstantin Haase Document different scopes/bindings.
rkh authored
915
916 * Your application class body
917 * Methods defined by extensions
918 * The block passed to `helpers`
919 * Procs/blocks used as value for `set`
920
921 You can reach the scope object (the class) like this:
922
6233ce4 Konstantin Haase Proof-reading Scopes section
rkh authored
923 * Via the object passed to configure blocks (<tt>configure { |c| ... }</tt>)
3f21c3f Konstantin Haase Document different scopes/bindings.
rkh authored
924 * `settings` from within request scope
925
926 === Request/Instance Scope
927
6233ce4 Konstantin Haase Proof-reading Scopes section
rkh authored
928 For every incoming request, a new instance of your application class is
929 created and all handler blocks run in that scope. From within this scope you
930 can access the `request` and `session` object or call rendering methods like
931 `erb` or `haml`. You can access the application scope from within the request
932 scope via the `settings` helper:
3f21c3f Konstantin Haase Document different scopes/bindings.
rkh authored
933
934 class MyApp << Sinatra::Base
935 # Hey, I'm in the application scope!
936 get '/define_route/:name' do
937 # Request scope for '/define_route/:name'
938 @value = 42
939
940 settings.get("/#{params[:name]}") do
941 # Request scope for "/#{params[:name]}"
942 @value # => nil (not the same request)
943 end
944
945 "Route defined!"
946 end
947 end
948
6233ce4 Konstantin Haase Proof-reading Scopes section
rkh authored
949 You have the request scope binding inside:
3f21c3f Konstantin Haase Document different scopes/bindings.
rkh authored
950
951 * get/head/post/put/delete blocks
952 * before/after filters
953 * helper methods
954 * templates/views
955
956 === Delegation Scope
957
958 The delegation scope just forwards methods to the class scope. However, it
6233ce4 Konstantin Haase Proof-reading Scopes section
rkh authored
959 does not behave 100% like the class scope, as you do not have the class'
960 binding: Only methods explicitly marked for delegation are available and you
961 do not share variables/state with the class scope (read: you have a different
962 `self`). You can explicitly add method delegations by calling
963 <tt>Sinatra::Delegator.delegate :method_name</tt>.
3f21c3f Konstantin Haase Document different scopes/bindings.
rkh authored
964
6233ce4 Konstantin Haase Proof-reading Scopes section
rkh authored
965 You have the delegate scope binding inside:
3f21c3f Konstantin Haase Document different scopes/bindings.
rkh authored
966
967 * The top level binding, if you did <tt>require "sinatra"</tt>
6233ce4 Konstantin Haase Proof-reading Scopes section
rkh authored
968 * An object extended with the `Sinatra::Delegator` mixin
3f21c3f Konstantin Haase Document different scopes/bindings.
rkh authored
969
2e2e595 Konstantin Haase Remove Sinatra::Delegator sidebar (now covered by Scopes), keep "Have a ...
rkh authored
970 Have a look at the code for yourself: here's the
971 {Sinatra::Delegator mixin}[http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/base.rb#L1128]
69791f7 Konstantin Haase Minor README adjustments.
rkh authored
972 being {included into the main namespace}[http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/main.rb#L28].
2e2e595 Konstantin Haase Remove Sinatra::Delegator sidebar (now covered by Scopes), keep "Have a ...
rkh authored
973
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
974 == Command line
1776a80 Added Version and Docs
Blake Mizerany authored
975
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
976 Sinatra applications can be run directly:
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
977
4d61607 Simon Rozet update README/CHANGES re. -o
sr authored
978 ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER]
1776a80 Added Version and Docs
Blake Mizerany authored
979
980 Options are:
981
982 -h # help
983 -p # set the port (default is 4567)
4d61607 Simon Rozet update README/CHANGES re. -o
sr authored
984 -o # set the host (default is 0.0.0.0)
1776a80 Added Version and Docs
Blake Mizerany authored
985 -e # set the environment (default is development)
f29486b Karel Minarik Note "-s" (server) command line option in README
karmi authored
986 -s # specify rack server/handler (default is thin)
e7e0e55 Ryan Tomayko Minor docfixes in README.rdoc
rtomayko authored
987 -x # turn on the mutex lock (default is off)
1776a80 Added Version and Docs
Blake Mizerany authored
988
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
989 == The Bleeding Edge
6326809 Markus Prinz Add a subsection about tools needed for Sinatra to the Contributing sect...
cypher authored
990
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
991 If you would like to use Sinatra's latest bleeding code, create a local
992 clone and run your app with the <tt>sinatra/lib</tt> directory on the
993 <tt>LOAD_PATH</tt>:
6326809 Markus Prinz Add a subsection about tools needed for Sinatra to the Contributing sect...
cypher authored
994
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
995 cd myapp
ba92616 Blake Mizerany Updated README to point to github.com/sinatra/sinatra.git
bmizerany authored
996 git clone git://github.com/sinatra/sinatra.git
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
997 ruby -Isinatra/lib myapp.rb
480fbfa Ryan Tomayko minor formatting tweaks to cypher's README updates
rtomayko authored
998
4f30c1c fix unclosed <tt> in README
Mathew Cucuzella authored
999 Alternatively, you can add the <tt>sinatra/lib</tt> directory to the
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
1000 <tt>LOAD_PATH</tt> in your application:
1776a80 Added Version and Docs
Blake Mizerany authored
1001
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1002 $LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib'
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
1003 require 'rubygems'
1776a80 Added Version and Docs
Blake Mizerany authored
1004 require 'sinatra'
1005
1006 get '/about' do
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
1007 "I'm running version " + Sinatra::VERSION
1776a80 Added Version and Docs
Blake Mizerany authored
1008 end
e6c5471 Markus Prinz Add a community section with info about the mailing list and irc channel
cypher authored
1009
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
1010 To update the Sinatra sources in the future:
d8fec16 Markus Prinz Add subsection about contributing a patch as well as a link to the issue...
cypher authored
1011
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
1012 cd myproject/sinatra
1013 git pull
e6c5471 Markus Prinz Add a community section with info about the mailing list and irc channel
cypher authored
1014
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
1015 == More
e6c5471 Markus Prinz Add a community section with info about the mailing list and irc channel
cypher authored
1016
754f116 Ryan Tomayko README: better links to project website and mailing list
rtomayko authored
1017 * {Project Website}[http://www.sinatrarb.com/] - Additional documentation,
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
1018 news, and links to other resources.
754f116 Ryan Tomayko README: better links to project website and mailing list
rtomayko authored
1019 * {Contributing}[http://www.sinatrarb.com/contributing] - Find a bug? Need
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
1020 help? Have a patch?
60ac449 Simon Rozet lighthouse => github issue
sr authored
1021 * {Issue tracker}[http://github.com/sinatra/sinatra/issues]
5018264 Ryan Tomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
1022 * {Twitter}[http://twitter.com/sinatra]
754f116 Ryan Tomayko README: better links to project website and mailing list
rtomayko authored
1023 * {Mailing List}[http://groups.google.com/group/sinatrarb/topics]
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
1024 * {IRC: #sinatra}[irc://chat.freenode.net/#sinatra] on http://freenode.net
Something went wrong with that request. Please try again.