Skip to content
This repository
Newer
Older
100644 851 lines (598 sloc) 22.267 kb
df800b5c »
2008-03-24 Docs are started
1 = Sinatra
2
4c91e540 »
2009-04-20 Web applications should not be hyphenated
3 Sinatra is a DSL for quickly creating web applications in Ruby with minimal
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
4 effort:
df800b5c »
2008-03-24 Docs are started
5
6 # myapp.rb
7 require 'sinatra'
6306a9f2 »
2010-09-07 minor adjustments and fixes for the readme examples
8
df800b5c »
2008-03-24 Docs are started
9 get '/' do
10 'Hello world!'
11 end
12
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
13 Install the gem and run with:
df800b5c »
2008-03-24 Docs are started
14
a8b23ca0 »
2010-09-07 Avoid `require "rubygems"` and `sudo` in README.
15 gem install sinatra
16 ruby -rubygems myapp.rb
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
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:
df800b5c »
2008-03-24 Docs are started
24
25 get '/' do
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
26 .. show something ..
df800b5c »
2008-03-24 Docs are started
27 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
28
df800b5c »
2008-03-24 Docs are started
29 post '/' do
30 .. create something ..
31 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
32
df800b5c »
2008-03-24 Docs are started
33 put '/' do
34 .. update something ..
35 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
36
df800b5c »
2008-03-24 Docs are started
37 delete '/' do
38 .. annihilate something ..
39 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
40
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
41 Routes are matched in the order they are defined. The first route that
f44fb6aa »
2008-08-31 grammar/formatting pass over README
42 matches the request is invoked.
1776a80d »
2008-03-24 Added Version and Docs
43
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
44 Route patterns may include named parameters, accessible via the
45 <tt>params</tt> hash:
1776a80d »
2008-03-24 Added Version and Docs
46
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
47 get '/hello/:name' do
ce0fe87a »
2009-05-20 fix inaccurate comment in README
48 # matches "GET /hello/foo" and "GET /hello/bar"
a734cf38 »
2008-12-13 I knew I shoulda taken that left turn at Hoboken
49 # params[:name] is 'foo' or 'bar'
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
50 "Hello #{params[:name]}!"
1776a80d »
2008-03-24 Added Version and Docs
51 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
52
6569d1b0 »
2009-01-28 Added route block params in routing statements [#140]
53 You can also access named parameters via block parameters:
54
55 get '/hello/:name' do |n|
56 "Hello #{n}!"
57 end
58
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
59 Route patterns may also include splat (or wildcard) parameters, accessible
60 via the <tt>params[:splat]</tt> array.
1776a80d »
2008-03-24 Added Version and Docs
61
9c85e99c »
2008-04-24 Specs, documentation and fixes for splat'n routes
62 get '/say/*/to/*' do
63 # matches /say/hello/to/world
a734cf38 »
2008-12-13 I knew I shoulda taken that left turn at Hoboken
64 params[:splat] # => ["hello", "world"]
9c85e99c »
2008-04-24 Specs, documentation and fixes for splat'n routes
65 end
66
67 get '/download/*.*' do
68 # matches /download/path/to/file.xml
a734cf38 »
2008-12-13 I knew I shoulda taken that left turn at Hoboken
69 params[:splat] # => ["path/to/file", "xml"]
1776a80d »
2008-03-24 Added Version and Docs
70 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
71
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
72 Route matching with Regular Expressions:
73
74 get %r{/hello/([\w]+)} do
75 "Hello, #{params[:captures].first}!"
76 end
77
6569d1b0 »
2009-01-28 Added route block params in routing statements [#140]
78 Or with a block parameter:
79
80 get %r{/hello/([\w]+)} do |c|
81 "Hello, #{c}!"
82 end
83
6602341b »
2010-09-02 Documentation for condition. Fixes GH #15.
84 === Conditions
85
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
86 Routes may include a variety of matching conditions, such as the user agent:
f44fb6aa »
2008-08-31 grammar/formatting pass over README
87
1776a80d »
2008-03-24 Added Version and Docs
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
a734cf38 »
2008-12-13 I knew I shoulda taken that left turn at Hoboken
93 # Matches non-songbird browsers
1776a80d »
2008-03-24 Added Version and Docs
94 end
df800b5c »
2008-03-24 Docs are started
95
e0a67f39 »
2010-09-03 fix markup for inline code in README
96 Other available conditions are +host_name+ and +provides+:
6602341b »
2010-09-02 Documentation for condition. Fixes GH #15.
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
9a2cdf9e »
2010-09-02 document route return values, fixes GH #23
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
b73158aa »
2010-09-10 Minor README improvements.
129 You can return any object that would either be a valid Rack response, Rack
130 body object or HTTP status code:
9a2cdf9e »
2010-09-02 document route return values, fixes GH #23
131
68e05d99 »
2010-09-03 fix markup for multi word inline code in README
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>
209989e4 »
2010-09-03 fix markup for multi word inline code in README, take two (apparently…
134 * An object that responds to <tt>#each</tt> and passes nothing but strings to the given block
9a2cdf9e »
2010-09-02 document route return values, fixes GH #23
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
9cbaa8ca »
2010-09-07 Simplify streaming example.
145 get('/') { Stream.new }
9a2cdf9e »
2010-09-02 document route return values, fixes GH #23
146
a734cf38 »
2008-12-13 I knew I shoulda taken that left turn at Hoboken
147 == Static Files
047edc6a »
2008-03-26 update README with Static help
148
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
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:
a734cf38 »
2008-12-13 I knew I shoulda taken that left turn at Hoboken
151
152 set :public, File.dirname(__FILE__) + '/static'
df800b5c »
2008-03-24 Docs are started
153
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
154 Note that the public directory name is not included in the URL. A file
85b4462b »
2009-01-24 README: fix formatting on static file note
155 <tt>./public/css/style.css</tt> is made available as
156 <tt>http://example.com/css/style.css</tt>.
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
157
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
158 == Views / Templates
df800b5c »
2008-03-24 Docs are started
159
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
160 Templates are assumed to be located directly under the <tt>./views</tt>
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
161 directory. To use a different views directory:
a734cf38 »
2008-12-13 I knew I shoulda taken that left turn at Hoboken
162
163 set :views, File.dirname(__FILE__) + '/templates'
164
06161bf7 »
2009-03-25 Note on passing template symbols vs. strings in README
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
caae141d »
2010-09-23 Added a transition to better explain that templates must be defined w…
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.
06161bf7 »
2009-03-25 Note on passing template symbols vs. strings in README
170
f44fb6aa »
2008-08-31 grammar/formatting pass over README
171 === Haml Templates
df800b5c »
2008-03-24 Docs are started
172
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
173 The haml gem/library is required to render HAML templates:
174
801163e9 »
2009-04-24 closes #9779 Auto-require haml/erb/builder/sass
175 ## You'll need to require haml in your app
176 require 'haml'
177
df800b5c »
2008-03-24 Docs are started
178 get '/' do
179 haml :index
180 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
181
182 Renders <tt>./views/index.haml</tt>.
183
13a2b951 »
2010-05-26 In README docs, fix links to HAML and SASS Options pages.
184 {Haml's options}[http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html#options]
d359dc9c »
2009-03-15 Merge app-level haml/sass options with call options [#184]
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
6306a9f2 »
2010-09-07 minor adjustments and fixes for the readme examples
189 set :haml, :format => :html5 # default Haml format is :xhtml
d359dc9c »
2009-03-15 Merge app-level haml/sass options with call options [#184]
190
191 get '/' do
6306a9f2 »
2010-09-07 minor adjustments and fixes for the readme examples
192 haml :index, :format => :html4 # overridden
d359dc9c »
2009-03-15 Merge app-level haml/sass options with call options [#184]
193 end
194
195
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
196 === Erb Templates
f44fb6aa »
2008-08-31 grammar/formatting pass over README
197
801163e9 »
2009-04-24 closes #9779 Auto-require haml/erb/builder/sass
198 ## You'll need to require erb in your app
199 require 'erb'
200
f44fb6aa »
2008-08-31 grammar/formatting pass over README
201 get '/' do
202 erb :index
203 end
204
205 Renders <tt>./views/index.erb</tt>
206
7c5d6937 »
2009-12-23 Doc for erubis
207 === Erubis
208
a9389aa3 »
2010-06-27 Correction to erubis template rendering instructions
209 The erubis gem/library is required to render erubis templates:
7c5d6937 »
2009-12-23 Doc for erubis
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
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
220 === Builder Templates
f44fb6aa »
2008-08-31 grammar/formatting pass over README
221
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
222 The builder gem/library is required to render builder templates:
df800b5c »
2008-03-24 Docs are started
223
801163e9 »
2009-04-24 closes #9779 Auto-require haml/erb/builder/sass
224 ## You'll need to require builder in your app
225 require 'builder'
226
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
227 get '/' do
228 content_type 'application/xml', :charset => 'utf-8'
229 builder :index
230 end
231
232 Renders <tt>./views/index.builder</tt>.
233
234 === Sass Templates
235
236 The sass gem/library is required to render Sass templates:
f44fb6aa »
2008-08-31 grammar/formatting pass over README
237
801163e9 »
2009-04-24 closes #9779 Auto-require haml/erb/builder/sass
238 ## You'll need to require haml or sass in your app
239 require 'sass'
240
4144ac1a »
2008-04-08 Added Sass information to documentation.
241 get '/stylesheet.css' do
ccc19b04 »
2008-04-13 content_type response helper with mime type lookup and parameter supp…
242 content_type 'text/css', :charset => 'utf-8'
4144ac1a »
2008-04-08 Added Sass information to documentation.
243 sass :stylesheet
244 end
245
f44fb6aa »
2008-08-31 grammar/formatting pass over README
246 Renders <tt>./views/stylesheet.sass</tt>.
247
13a2b951 »
2010-05-26 In README docs, fix links to HAML and SASS Options pages.
248 {Sass' options}[http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#options]
d359dc9c »
2009-03-15 Merge app-level haml/sass options with call options [#184]
249 can be set globally through Sinatra's configurations,
250 see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
251 and overridden on an individual basis.
252
6306a9f2 »
2010-09-07 minor adjustments and fixes for the readme examples
253 set :sass, :style => :compact # default Sass style is :nested
d359dc9c »
2009-03-15 Merge app-level haml/sass options with call options [#184]
254
255 get '/stylesheet.css' do
256 content_type 'text/css', :charset => 'utf-8'
b90d00c8 »
2009-12-19 Update sass example re. options
257 sass :stylesheet, :style => :expanded # overridden
d359dc9c »
2009-03-15 Merge app-level haml/sass options with call options [#184]
258 end
259
621bfcbd »
2010-03-01 Added Less support
260 === Less Templates
261
262 The less gem/library is required to render Less templates:
263
264 ## You'll need to require less in your app
265 require 'less'
266
267 get '/stylesheet.css' do
268 content_type 'text/css', :charset => 'utf-8'
269 less :stylesheet
270 end
271
272 Renders <tt>./views/stylesheet.less</tt>.
273
f44fb6aa »
2008-08-31 grammar/formatting pass over README
274 === Inline Templates
df800b5c »
2008-03-24 Docs are started
275
276 get '/' do
277 haml '%div.title Hello World'
278 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
279
280 Renders the inlined template string.
df800b5c »
2008-03-24 Docs are started
281
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
282 === Accessing Variables in Templates
df800b5c »
2008-03-24 Docs are started
283
5018264d »
2009-03-01 Tidy up README a bit; link to @sinatra on Twitter
284 Templates are evaluated within the same context as route handlers. Instance
285 variables set in route handlers are direcly accessible by templates:
df800b5c »
2008-03-24 Docs are started
286
287 get '/:id' do
288 @foo = Foo.find(params[:id])
95aca761 »
2008-11-30 fix documentation of variable interpolation into templates
289 haml '%h1= @foo.name'
df800b5c »
2008-03-24 Docs are started
290 end
291
f44fb6aa »
2008-08-31 grammar/formatting pass over README
292 Or, specify an explicit Hash of local variables:
df800b5c »
2008-03-24 Docs are started
293
294 get '/:id' do
f44fb6aa »
2008-08-31 grammar/formatting pass over README
295 foo = Foo.find(params[:id])
95aca761 »
2008-11-30 fix documentation of variable interpolation into templates
296 haml '%h1= foo.name', :locals => { :foo => foo }
df800b5c »
2008-03-24 Docs are started
297 end
298
f44fb6aa »
2008-08-31 grammar/formatting pass over README
299 This is typically used when rendering templates as partials from within
300 other templates.
301
3ef8eede »
2009-12-19 Deprecate use_in_file_templates!
302 === Inline Templates
83cba9cf »
2008-03-29 updated README with helpful tidbits
303
f44fb6aa »
2008-08-31 grammar/formatting pass over README
304 Templates may be defined at the end of the source file:
83cba9cf »
2008-03-29 updated README with helpful tidbits
305
eec7d214 »
2009-01-16 In-file-templates are automaticly loaded for you.
306 require 'sinatra'
307
83cba9cf »
2008-03-29 updated README with helpful tidbits
308 get '/' do
309 haml :index
310 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
311
83cba9cf »
2008-03-29 updated README with helpful tidbits
312 __END__
f44fb6aa »
2008-08-31 grammar/formatting pass over README
313
f71330e6 »
2008-05-07 quick doc fix
314 @@ layout
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
315 %html
316 = yield
f44fb6aa »
2008-08-31 grammar/formatting pass over README
317
f71330e6 »
2008-05-07 quick doc fix
318 @@ index
83cba9cf »
2008-03-29 updated README with helpful tidbits
319 %div.title Hello world!!!!!
320
a0ba2c8a »
2010-10-12 Minor markup fix in README.
321 NOTE: Inline templates defined in the source file that requires sinatra are
6e88b740 »
2010-10-12 Fix the minor markup fix in README.
322 automatically loaded. Call <tt>enable :inline_templates</tt> explicitly if you
3ef8eede »
2009-12-19 Deprecate use_in_file_templates!
323 have inline templates in other source files.
eec7d214 »
2009-01-16 In-file-templates are automaticly loaded for you.
324
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
325 === Named Templates
326
5018264d »
2009-03-01 Tidy up README a bit; link to @sinatra on Twitter
327 Templates may also be defined using the top-level <tt>template</tt> method:
83cba9cf »
2008-03-29 updated README with helpful tidbits
328
329 template :layout do
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
330 "%html\n =yield\n"
83cba9cf »
2008-03-29 updated README with helpful tidbits
331 end
332
333 template :index do
334 '%div.title Hello World!'
335 end
336
337 get '/' do
338 haml :index
339 end
340
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
341 If a template named "layout" exists, it will be used each time a template
342 is rendered. You can disable layouts by passing <tt>:layout => false</tt>.
578bbabd »
2009-01-09 Updating README for :layout => true.
343
344 get '/' do
345 haml :index, :layout => !request.xhr?
346 end
347
f44fb6aa »
2008-08-31 grammar/formatting pass over README
348 == Helpers
df800b5c »
2008-03-24 Docs are started
349
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
350 Use the top-level <tt>helpers</tt> method to define helper methods for use in
5018264d »
2009-03-01 Tidy up README a bit; link to @sinatra on Twitter
351 route handlers and templates:
df800b5c »
2008-03-24 Docs are started
352
353 helpers do
354 def bar(name)
355 "#{name}bar"
356 end
357 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
358
1776a80d »
2008-03-24 Added Version and Docs
359 get '/:name' do
360 bar(params[:name])
361 end
df800b5c »
2008-03-24 Docs are started
362
f44fb6aa »
2008-08-31 grammar/formatting pass over README
363 == Filters
df800b5c »
2008-03-24 Docs are started
364
b73158aa »
2010-09-10 Minor README improvements.
365 Before filters are evaluated before each request within the same context as
366 the routes will be and can modify the request and response. Instance variables
367 set in filters are accessible by routes and templates:
1776a80d »
2008-03-24 Added Version and Docs
368
df800b5c »
2008-03-24 Docs are started
369 before do
a734cf38 »
2008-12-13 I knew I shoulda taken that left turn at Hoboken
370 @note = 'Hi!'
371 request.path_info = '/foo/bar/baz'
372 end
373
374 get '/foo/*' do
375 @note #=> 'Hi!'
376 params[:splat] #=> 'bar/baz'
df800b5c »
2008-03-24 Docs are started
377 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
378
b73158aa »
2010-09-10 Minor README improvements.
379 After filter are evaluated after each request within the same context and can
380 also modify the request and response. Instance variables set in before filters
381 and routes are accessible by after filters:
4e50ddbc »
2008-12-21 Adds after filters
382
383 after do
384 puts response.status
385 end
386
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
387 == Halting
a734cf38 »
2008-12-13 I knew I shoulda taken that left turn at Hoboken
388
4e50ddbc »
2008-12-21 Adds after filters
389 To immediately stop a request within a filter or route use:
df800b5c »
2008-03-24 Docs are started
390
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
391 halt
f44fb6aa »
2008-08-31 grammar/formatting pass over README
392
b73158aa »
2010-09-10 Minor README improvements.
393 You can also specify the status when halting:
fbbd8227 »
2009-12-19 More 'halt' doc
394
395 halt 410
396
b73158aa »
2010-09-10 Minor README improvements.
397 Or the body:
df800b5c »
2008-03-24 Docs are started
398
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
399 halt 'this will be the body'
df800b5c »
2008-03-24 Docs are started
400
b73158aa »
2010-09-10 Minor README improvements.
401 Or both:
f44fb6aa »
2008-08-31 grammar/formatting pass over README
402
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
403 halt 401, 'go away!'
df800b5c »
2008-03-24 Docs are started
404
b73158aa »
2010-09-10 Minor README improvements.
405 With headers:
fbbd8227 »
2009-12-19 More 'halt' doc
406
407 halt 402, {'Content-Type' => 'text/plain'}, 'revenge'
408
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
409 == Passing
f44fb6aa »
2008-08-31 grammar/formatting pass over README
410
5018264d »
2009-03-01 Tidy up README a bit; link to @sinatra on Twitter
411 A route can punt processing to the next matching route using <tt>pass</tt>:
df800b5c »
2008-03-24 Docs are started
412
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
413 get '/guess/:who' do
414 pass unless params[:who] == 'Frank'
6c9488e2 »
2009-12-23 Stick to single quote; kill a blank line
415 'You got me!'
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
416 end
417
418 get '/guess/*' do
6c9488e2 »
2009-12-23 Stick to single quote; kill a blank line
419 'You missed!'
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
420 end
421
422 The route block is immediately exited and control continues with the next
423 matching route. If no matching route is found, a 404 is returned.
df800b5c »
2008-03-24 Docs are started
424
a51e2f8f »
2010-10-11 Document request object. Fixes GH #60.
425 == Accessing the Request Object
426
83298879 »
2010-10-11 Fix typo in README.
427 The incoming request object can be accessed from request level (filter, routes, error handlers) through the `request` method:
a51e2f8f »
2010-10-11 Document request object. Fixes GH #60.
428
429 # app running on http://example.com/example
430 get '/foo' do
431 request.body # request body sent by the client (see below)
432 request.scheme # "http"
433 request.script_name # "/example"
434 request.path_info # "/foo"
435 request.port # 80
436 request.request_method # "GET"
437 request.query_string # ""
438 request.content_length # length of request.body
439 request.media_type # media type of request.body
440 request.host # "example.com"
441 request.get? # true (similar methods for other verbs)
442 request.form_data? # false
443 request["SOME_HEADER"] # value of SOME_HEADER header
444 request.referer # the referer of the client or '/'
445 request.user_agent # user agent (used by :agent condition)
446 request.cookies # hash of browser cookies
447 request.xhr? # is this an ajax request?
448 request.url # "http://example.com/example/foo"
449 request.path # "/example/foo"
450 request.ip # client IP address
451 request.secure? # false
452 requuest.env # raw env hash handed in by Rack
453 end
454
c802df84 »
2010-10-11 Fix markup
455 Some options, like <tt>script_name</tt> or <tt>path_info</tt> can also be
456 written:
a51e2f8f »
2010-10-11 Document request object. Fixes GH #60.
457
458 before { request.path_info = "/" }
459
460 get "/" do
461 "all requests end up here"
462 end
463
464 The <tt>request.body</tt> is an IO or StringIO object:
465
466 post "/api" do
467 request.body.rewind # in case someone already read it
468 data = JSON.parse request.body.read
469 "Hello #{data['name']}!"
470 end
471
13fc79d3 »
2009-03-24 Remove support for source file reloading [#166]
472 == Configuration
1776a80d »
2008-03-24 Added Version and Docs
473
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
474 Run once, at startup, in any environment:
1776a80d »
2008-03-24 Added Version and Docs
475
476 configure do
e75f4b3f »
2008-09-09 misc README formatting tweaks
477 ...
1776a80d »
2008-03-24 Added Version and Docs
478 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
479
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
480 Run only when the environment (RACK_ENV environment variable) is set to
13fc79d3 »
2009-03-24 Remove support for source file reloading [#166]
481 <tt>:production</tt>:
1776a80d »
2008-03-24 Added Version and Docs
482
483 configure :production do
e75f4b3f »
2008-09-09 misc README formatting tweaks
484 ...
1776a80d »
2008-03-24 Added Version and Docs
485 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
486
13fc79d3 »
2009-03-24 Remove support for source file reloading [#166]
487 Run when the environment is set to either <tt>:production</tt> or
488 <tt>:test</tt>:
1776a80d »
2008-03-24 Added Version and Docs
489
490 configure :production, :test do
e75f4b3f »
2008-09-09 misc README formatting tweaks
491 ...
1776a80d »
2008-03-24 Added Version and Docs
492 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
493
e75f4b3f »
2008-09-09 misc README formatting tweaks
494 == Error handling
1776a80d »
2008-03-24 Added Version and Docs
495
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
496 Error handlers run within the same context as routes and before filters, which
b73158aa »
2010-09-10 Minor README improvements.
497 means you get all the goodies it has to offer, like <tt>haml</tt>,
498 <tt>erb</tt>, <tt>halt</tt>, etc.
1776a80d »
2008-03-24 Added Version and Docs
499
e75f4b3f »
2008-09-09 misc README formatting tweaks
500 === Not Found
1776a80d »
2008-03-24 Added Version and Docs
501
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
502 When a <tt>Sinatra::NotFound</tt> exception is raised, or the response's status
503 code is 404, the <tt>not_found</tt> handler is invoked:
1776a80d »
2008-03-24 Added Version and Docs
504
505 not_found do
b73158aa »
2010-09-10 Minor README improvements.
506 'This is nowhere to be found.'
1776a80d »
2008-03-24 Added Version and Docs
507 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
508
e75f4b3f »
2008-09-09 misc README formatting tweaks
509 === Error
83cba9cf »
2008-03-29 updated README with helpful tidbits
510
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
511 The +error+ handler is invoked any time an exception is raised from a route
63fd7734 »
2009-12-19 Small doc fix re. after filter
512 block or a filter. The exception object can be obtained from the
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
513 <tt>sinatra.error</tt> Rack variable:
83cba9cf »
2008-03-29 updated README with helpful tidbits
514
1776a80d »
2008-03-24 Added Version and Docs
515 error do
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
516 'Sorry there was a nasty error - ' + env['sinatra.error'].name
83cba9cf »
2008-03-29 updated README with helpful tidbits
517 end
518
e75f4b3f »
2008-09-09 misc README formatting tweaks
519 Custom errors:
83cba9cf »
2008-03-29 updated README with helpful tidbits
520
521 error MyCustomError do
e7e0e558 »
2008-04-14 Minor docfixes in README.rdoc
522 'So what happened was...' + request.env['sinatra.error'].message
1776a80d »
2008-03-24 Added Version and Docs
523 end
83cba9cf »
2008-03-29 updated README with helpful tidbits
524
e75f4b3f »
2008-09-09 misc README formatting tweaks
525 Then, if this happens:
83cba9cf »
2008-03-29 updated README with helpful tidbits
526
527 get '/' do
528 raise MyCustomError, 'something bad'
529 end
530
e75f4b3f »
2008-09-09 misc README formatting tweaks
531 You get this:
83cba9cf »
2008-03-29 updated README with helpful tidbits
532
533 So what happened was... something bad
f44fb6aa »
2008-08-31 grammar/formatting pass over README
534
59e797e9 »
2009-12-23 Doc for error(500) { }
535 Alternatively, you can install error handler for a status code:
536
537 error 403 do
538 'Access forbidden'
539 end
540
541 get '/secret' do
542 403
543 end
544
545 Or a range:
546
547 error 400..510 do
548 'Boom'
549 end
550
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
551 Sinatra installs special <tt>not_found</tt> and <tt>error</tt> handlers when
552 running under the development environment.
83cba9cf »
2008-03-29 updated README with helpful tidbits
553
f44fb6aa »
2008-08-31 grammar/formatting pass over README
554 == Mime types
555
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
556 When using <tt>send_file</tt> or static files you may have mime types Sinatra
6d8b333a »
2009-10-18 Update README re. mime_type
557 doesn't understand. Use +mime_type+ to register them by file extension:
83cba9cf »
2008-03-29 updated README with helpful tidbits
558
6d8b333a »
2009-10-18 Update README re. mime_type
559 mime_type :foo, 'text/foo'
1776a80d »
2008-03-24 Added Version and Docs
560
cb8fcb63 »
2009-12-23 Doc for content_type :foo
561 You can also use it with the +content_type+ helper:
562
563 content_type :foo
564
f44fb6aa »
2008-08-31 grammar/formatting pass over README
565 == Rack Middleware
bda21f1f »
2008-05-19 add doc on using Rack middleware to README
566
f44fb6aa »
2008-08-31 grammar/formatting pass over README
567 Sinatra rides on Rack[http://rack.rubyforge.org/], a minimal standard
568 interface for Ruby web frameworks. One of Rack's most interesting capabilities
569 for application developers is support for "middleware" -- components that sit
570 between the server and your application monitoring and/or manipulating the
571 HTTP request/response to provide various types of common functionality.
bda21f1f »
2008-05-19 add doc on using Rack middleware to README
572
e75f4b3f »
2008-09-09 misc README formatting tweaks
573 Sinatra makes building Rack middleware pipelines a cinch via a top-level
574 +use+ method:
bda21f1f »
2008-05-19 add doc on using Rack middleware to README
575
576 require 'sinatra'
577 require 'my_custom_middleware'
578
579 use Rack::Lint
580 use MyCustomMiddleware
581
582 get '/hello' do
583 'Hello World'
584 end
585
f44fb6aa »
2008-08-31 grammar/formatting pass over README
586 The semantics of +use+ are identical to those defined for the
587 Rack::Builder[http://rack.rubyforge.org/doc/classes/Rack/Builder.html] DSL
588 (most frequently used from rackup files). For example, the +use+ method
589 accepts multiple/variable args as well as blocks:
bda21f1f »
2008-05-19 add doc on using Rack middleware to README
590
591 use Rack::Auth::Basic do |username, password|
592 username == 'admin' && password == 'secret'
593 end
594
f44fb6aa »
2008-08-31 grammar/formatting pass over README
595 Rack is distributed with a variety of standard middleware for logging,
596 debugging, URL routing, authentication, and session handling. Sinatra uses
597 many of of these components automatically based on configuration so you
598 typically don't have to +use+ them explicitly.
bda21f1f »
2008-05-19 add doc on using Rack middleware to README
599
f44fb6aa »
2008-08-31 grammar/formatting pass over README
600 == Testing
1776a80d »
2008-03-24 Added Version and Docs
601
c831278a »
2009-05-18 Recommend Rack::Test in README / note Sinatra::Test deprecation
602 Sinatra tests can be written using any Rack-based testing library
603 or framework. {Rack::Test}[http://gitrdoc.com/brynary/rack-test] is
604 recommended:
c00a25ee »
2009-01-13 Test framework refactoring
605
7cfe04a9 »
2008-09-24 Fix for test/unit and test/spec docs
606 require 'my_sinatra_app'
f2a328a1 »
2010-07-26 MOD: docs for testing forgot to require test/unit
607 require 'test/unit'
c831278a »
2009-05-18 Recommend Rack::Test in README / note Sinatra::Test deprecation
608 require 'rack/test'
f44fb6aa »
2008-08-31 grammar/formatting pass over README
609
1776a80d »
2008-03-24 Added Version and Docs
610 class MyAppTest < Test::Unit::TestCase
c831278a »
2009-05-18 Recommend Rack::Test in README / note Sinatra::Test deprecation
611 include Rack::Test::Methods
612
613 def app
614 Sinatra::Application
615 end
f44fb6aa »
2008-08-31 grammar/formatting pass over README
616
2f377e26 »
2009-03-01 Trim down Testing section in the README; link to doc site instead
617 def test_my_default
c00a25ee »
2009-01-13 Test framework refactoring
618 get '/'
c831278a »
2009-05-18 Recommend Rack::Test in README / note Sinatra::Test deprecation
619 assert_equal 'Hello World!', last_response.body
1776a80d »
2008-03-24 Added Version and Docs
620 end
10c90d5f »
2008-09-27 document testing with rspec
621
2f377e26 »
2009-03-01 Trim down Testing section in the README; link to doc site instead
622 def test_with_params
c831278a »
2009-05-18 Recommend Rack::Test in README / note Sinatra::Test deprecation
623 get '/meet', :name => 'Frank'
624 assert_equal 'Hello Frank!', last_response.body
10c90d5f »
2008-09-27 document testing with rspec
625 end
626
2f377e26 »
2009-03-01 Trim down Testing section in the README; link to doc site instead
627 def test_with_rack_env
c831278a »
2009-05-18 Recommend Rack::Test in README / note Sinatra::Test deprecation
628 get '/', {}, 'HTTP_USER_AGENT' => 'Songbird'
629 assert_equal "You're using Songbird!", last_response.body
1fb5b99d »
2009-01-09 Bacon support
630 end
631 end
632
c831278a »
2009-05-18 Recommend Rack::Test in README / note Sinatra::Test deprecation
633 NOTE: The built-in Sinatra::Test module and Sinatra::TestHarness class
634 are deprecated as of the 0.9.2 release.
1776a80d »
2008-03-24 Added Version and Docs
635
53603333 »
2009-06-06 Add a note about Sinatra::Base to the README
636 == Sinatra::Base - Middleware, Libraries, and Modular Apps
637
638 Defining your app at the top-level works well for micro-apps but has
f343874e »
2010-09-24 Minor README adjustments.
639 considerable drawbacks when building reusable components such as Rack
53603333 »
2009-06-06 Add a note about Sinatra::Base to the README
640 middleware, Rails metal, simple libraries with a server component, or
641 even Sinatra extensions. The top-level DSL pollutes the Object namespace
642 and assumes a micro-app style configuration (e.g., a single application
643 file, ./public and ./views directories, logging, exception detail page,
644 etc.). That's where Sinatra::Base comes into play:
645
646 require 'sinatra/base'
647
648 class MyApp < Sinatra::Base
649 set :sessions, true
650 set :foo, 'bar'
651
652 get '/' do
653 'Hello world!'
654 end
655 end
656
657 The MyApp class is an independent Rack component that can act as
658 Rack middleware, a Rack application, or Rails metal. You can +use+ or
659 +run+ this class from a rackup +config.ru+ file; or, control a server
660 component shipped as a library:
661
662 MyApp.run! :host => 'localhost', :port => 9090
663
664 The methods available to Sinatra::Base subclasses are exactly as those
665 available via the top-level DSL. Most top-level apps can be converted to
666 Sinatra::Base components with two modifications:
667
668 * Your file should require +sinatra/base+ instead of +sinatra+;
669 otherwise, all of Sinatra's DSL methods are imported into the main
670 namespace.
671 * Put your app's routes, error handlers, filters, and options in a subclass
672 of Sinatra::Base.
673
b67573fe »
2010-10-12 Yet another markup fix for the README.
674 <tt>Sinatra::Base</tt> is a blank slate. Most options are disabled by default,
53603333 »
2009-06-06 Add a note about Sinatra::Base to the README
675 including the built-in server. See {Options and Configuration}[http://sinatra.github.com/configuration.html]
676 for details on available options and their behavior.
677
f343874e »
2010-09-24 Minor README adjustments.
678 === Using Sinatra as Middleware
18368e9b »
2010-09-24 Added "Using Sinatra as middleware" section, fixes GH #19.
679
680 Not only is Sinatra able to use other Rack middleware, any Sinatra application
681 can in turn be added in front of any Rack endpoint as middleware itself. This
682 endpoint could be another Sinatra application, or any other Rack-based
683 application (Rails/Ramaze/Camping/...).
684
685 require 'sinatra/base'
686
687 class LoginScreen < Sinatra::Base
688 enable :session
689
690 get('/login') { haml :login }
691
692 post('/login') do
693 if params[:name] = 'admin' and params[:password] = 'admin'
694 session['user_name'] = params[:name]
695 else
696 redirect '/login'
697 end
698 end
699 end
700
701 class MyApp < Sinatra::Base
702 # middleware will run before filters
703 use LoginScreen
704
705 before do
706 unless session['user_name']
707 halt "Access denied, please <a href='/login'>login</a>."
708 end
709 end
710
711 get('/') { "Hello #{session['user_name']}." }
712 end
713
e2484e9c »
2010-09-24 Document different scopes/bindings.
714 == Scopes and Binding
715
4842814e »
2010-09-24 Proof-reading Scopes section
716 The scope you are currently in determines what methods and variables are
717 available.
e2484e9c »
2010-09-24 Document different scopes/bindings.
718
719 === Application/Class Scope
720
721 Every Sinatra application corresponds to a subclass of Sinatra::Base. If you
722 are using the top level DSL (<tt>require 'sinatra'</tt>), then this class is
723 Sinatra::Application, otherwise it is the subclass you created explicitly. At
724 class level you have methods like `get` or `before`, but you cannot access the
725 `request` object or the `session`, as there only is a single application class
726 for all requests.
727
728 Options created via `set` are methods at class level:
729
730 class MyApp << Sinatra::Base
731 # Hey, I'm in the application scope!
732 set :foo, 42
733 foo # => 42
734
735 get '/foo' do
736 # Hey, I'm no longer in the application scope!
737 end
738 end
739
4842814e »
2010-09-24 Proof-reading Scopes section
740 You have the application scope binding inside:
e2484e9c »
2010-09-24 Document different scopes/bindings.
741
742 * Your application class body
743 * Methods defined by extensions
744 * The block passed to `helpers`
745 * Procs/blocks used as value for `set`
746
747 You can reach the scope object (the class) like this:
748
4842814e »
2010-09-24 Proof-reading Scopes section
749 * Via the object passed to configure blocks (<tt>configure { |c| ... }</tt>)
e2484e9c »
2010-09-24 Document different scopes/bindings.
750 * `settings` from within request scope
751
752 === Request/Instance Scope
753
4842814e »
2010-09-24 Proof-reading Scopes section
754 For every incoming request, a new instance of your application class is
755 created and all handler blocks run in that scope. From within this scope you
756 can access the `request` and `session` object or call rendering methods like
757 `erb` or `haml`. You can access the application scope from within the request
758 scope via the `settings` helper:
e2484e9c »
2010-09-24 Document different scopes/bindings.
759
760 class MyApp << Sinatra::Base
761 # Hey, I'm in the application scope!
762 get '/define_route/:name' do
763 # Request scope for '/define_route/:name'
764 @value = 42
765
766 settings.get("/#{params[:name]}") do
767 # Request scope for "/#{params[:name]}"
768 @value # => nil (not the same request)
769 end
770
771 "Route defined!"
772 end
773 end
774
4842814e »
2010-09-24 Proof-reading Scopes section
775 You have the request scope binding inside:
e2484e9c »
2010-09-24 Document different scopes/bindings.
776
777 * get/head/post/put/delete blocks
778 * before/after filters
779 * helper methods
780 * templates/views
781
782 === Delegation Scope
783
784 The delegation scope just forwards methods to the class scope. However, it
4842814e »
2010-09-24 Proof-reading Scopes section
785 does not behave 100% like the class scope, as you do not have the class'
786 binding: Only methods explicitly marked for delegation are available and you
787 do not share variables/state with the class scope (read: you have a different
788 `self`). You can explicitly add method delegations by calling
789 <tt>Sinatra::Delegator.delegate :method_name</tt>.
e2484e9c »
2010-09-24 Document different scopes/bindings.
790
4842814e »
2010-09-24 Proof-reading Scopes section
791 You have the delegate scope binding inside:
e2484e9c »
2010-09-24 Document different scopes/bindings.
792
793 * The top level binding, if you did <tt>require "sinatra"</tt>
4842814e »
2010-09-24 Proof-reading Scopes section
794 * An object extended with the `Sinatra::Delegator` mixin
e2484e9c »
2010-09-24 Document different scopes/bindings.
795
400d2cc7 »
2010-09-24 Remove Sinatra::Delegator sidebar (now covered by Scopes), keep "Have…
796 Have a look at the code for yourself: here's the
797 {Sinatra::Delegator mixin}[http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/base.rb#L1128]
f343874e »
2010-09-24 Minor README adjustments.
798 being {included into the main namespace}[http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/main.rb#L28].
400d2cc7 »
2010-09-24 Remove Sinatra::Delegator sidebar (now covered by Scopes), keep "Have…
799
f44fb6aa »
2008-08-31 grammar/formatting pass over README
800 == Command line
1776a80d »
2008-03-24 Added Version and Docs
801
e75f4b3f »
2008-09-09 misc README formatting tweaks
802 Sinatra applications can be run directly:
f44fb6aa »
2008-08-31 grammar/formatting pass over README
803
4d616071 »
2010-03-01 update README/CHANGES re. -o
804 ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER]
1776a80d »
2008-03-24 Added Version and Docs
805
806 Options are:
807
808 -h # help
809 -p # set the port (default is 4567)
4d616071 »
2010-03-01 update README/CHANGES re. -o
810 -o # set the host (default is 0.0.0.0)
1776a80d »
2008-03-24 Added Version and Docs
811 -e # set the environment (default is development)
f29486ba »
2009-01-15 Note "-s" (server) command line option in README
812 -s # specify rack server/handler (default is thin)
e7e0e558 »
2008-04-14 Minor docfixes in README.rdoc
813 -x # turn on the mutex lock (default is off)
1776a80d »
2008-03-24 Added Version and Docs
814
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
815 == The Bleeding Edge
6326809e »
2008-08-31 Add a subsection about tools needed for Sinatra to the Contributing s…
816
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
817 If you would like to use Sinatra's latest bleeding code, create a local
818 clone and run your app with the <tt>sinatra/lib</tt> directory on the
819 <tt>LOAD_PATH</tt>:
6326809e »
2008-08-31 Add a subsection about tools needed for Sinatra to the Contributing s…
820
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
821 cd myapp
ba92616e »
2009-01-18 Updated README to point to github.com/sinatra/sinatra.git
822 git clone git://github.com/sinatra/sinatra.git
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
823 ruby -Isinatra/lib myapp.rb
480fbfa7 »
2008-08-31 minor formatting tweaks to cypher's README updates
824
4f30c1ce »
2009-05-12 fix unclosed <tt> in README
825 Alternatively, you can add the <tt>sinatra/lib</tt> directory to the
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
826 <tt>LOAD_PATH</tt> in your application:
1776a80d »
2008-03-24 Added Version and Docs
827
17cb177e »
2009-01-11 README and CHANGES tweaks for 0.9.0 release (#63)
828 $LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib'
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
829 require 'rubygems'
1776a80d »
2008-03-24 Added Version and Docs
830 require 'sinatra'
831
832 get '/about' do
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
833 "I'm running version " + Sinatra::VERSION
1776a80d »
2008-03-24 Added Version and Docs
834 end
e6c5471a »
2008-08-31 Add a community section with info about the mailing list and irc channel
835
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
836 To update the Sinatra sources in the future:
d8fec168 »
2008-08-31 Add subsection about contributing a patch as well as a link to the is…
837
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
838 cd myproject/sinatra
839 git pull
e6c5471a »
2008-08-31 Add a community section with info about the mailing list and irc channel
840
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
841 == More
e6c5471a »
2008-08-31 Add a community section with info about the mailing list and irc channel
842
754f116a »
2010-03-07 README: better links to project website and mailing list
843 * {Project Website}[http://www.sinatrarb.com/] - Additional documentation,
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
844 news, and links to other resources.
754f116a »
2010-03-07 README: better links to project website and mailing list
845 * {Contributing}[http://www.sinatrarb.com/contributing] - Find a bug? Need
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
846 help? Have a patch?
1d650315 »
2010-07-01 lighthouse => github issue
847 * {Issue tracker}[http://github.com/sinatra/sinatra/issues]
5018264d »
2009-03-01 Tidy up README a bit; link to @sinatra on Twitter
848 * {Twitter}[http://twitter.com/sinatra]
754f116a »
2010-03-07 README: better links to project website and mailing list
849 * {Mailing List}[http://groups.google.com/group/sinatrarb/topics]
4298a777 »
2009-01-23 Tweak README formatting; move community/contributing to website
850 * {IRC: #sinatra}[irc://chat.freenode.net/#sinatra] on http://freenode.net
Something went wrong with that request. Please try again.