Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 648 lines (448 sloc) 16.069 kB
df800b5 Docs are started
Blake Mizerany authored
1 = Sinatra
2
4c91e54 @watchdogtimer Web applications should not be hyphenated
watchdogtimer authored
3 Sinatra is a DSL for quickly creating web applications in Ruby with minimal
17cb177 @cypher 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 'rubygems'
8 require 'sinatra'
9 get '/' do
10 'Hello world!'
11 end
12
4298a77 @rtomayko 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
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
15 sudo gem install sinatra
16 ruby myapp.rb
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 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
26 .. show something ..
df800b5 Docs are started
Blake Mizerany authored
27 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
28
df800b5 Docs are started
Blake Mizerany authored
29 post '/' do
30 .. create something ..
31 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
32
df800b5 Docs are started
Blake Mizerany authored
33 put '/' do
34 .. update something ..
35 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
36
df800b5 Docs are started
Blake Mizerany authored
37 delete '/' do
38 .. annihilate something ..
39 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
40
4298a77 @rtomayko 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 @rtomayko grammar/formatting pass over README
rtomayko authored
42 matches the request is invoked.
1776a80 Added Version and Docs
Blake Mizerany authored
43
17cb177 @cypher 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 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
47 get '/hello/:name' do
ce0fe87 @scottj97 fix inaccurate comment in README
scottj97 authored
48 # matches "GET /hello/foo" and "GET /hello/bar"
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
49 # params[:name] is 'foo' or 'bar'
17cb177 @cypher 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 @rtomayko grammar/formatting pass over README
rtomayko authored
52
6569d1b @bdimcheff 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 @cypher 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 @vic Specs, documentation and fixes for splat'n routes
vic authored
62 get '/say/*/to/*' do
63 # matches /say/hello/to/world
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
64 params[:splat] # => ["hello", "world"]
9c85e99 @vic 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 @rtomayko 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 @rtomayko grammar/formatting pass over README
rtomayko authored
71
17cb177 @cypher 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 @bdimcheff 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
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
84 Routes may include a variety of matching conditions, such as the user agent:
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
85
1776a80 Added Version and Docs
Blake Mizerany authored
86 get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
87 "You're using Songbird version #{params[:agent][0]}"
88 end
89
90 get '/foo' do
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
91 # Matches non-songbird browsers
1776a80 Added Version and Docs
Blake Mizerany authored
92 end
df800b5 Docs are started
Blake Mizerany authored
93
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
94 == Static Files
047edc6 update README with Static help
Blake Mizerany authored
95
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
96 Static files are served from the <tt>./public</tt> directory. You can specify
97 a different location by setting the <tt>:public</tt> option:
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
98
99 set :public, File.dirname(__FILE__) + '/static'
df800b5 Docs are started
Blake Mizerany authored
100
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
101 Note that the public directory name is not included in the URL. A file
85b4462 @rtomayko README: fix formatting on static file note
rtomayko authored
102 <tt>./public/css/style.css</tt> is made available as
103 <tt>http://example.com/css/style.css</tt>.
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
104
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
105 == Views / Templates
df800b5 Docs are started
Blake Mizerany authored
106
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
107 Templates are assumed to be located directly under the <tt>./views</tt>
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
108 directory. To use a different views directory:
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
109
110 set :views, File.dirname(__FILE__) + '/templates'
111
06161bf @cypher Note on passing template symbols vs. strings in README
cypher authored
112 One important thing to remember is that you always have to reference
113 templates with symbols, even if they're in a subdirectory (in this
114 case use <tt>:'subdir/template'</tt>). Rendering methods will render
115 any strings passed to them directly.
116
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
117 === Haml Templates
df800b5 Docs are started
Blake Mizerany authored
118
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
119 The haml gem/library is required to render HAML templates:
120
801163e @bmizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
121 ## You'll need to require haml in your app
122 require 'haml'
123
df800b5 Docs are started
Blake Mizerany authored
124 get '/' do
125 haml :index
126 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
127
128 Renders <tt>./views/index.haml</tt>.
129
0321ada @dougireton In README docs, fix links to HAML and SASS Options pages.
dougireton authored
130 {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
131 can be set globally through Sinatra's configurations,
132 see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
133 and overridden on an individual basis.
134
135 set :haml, {:format => :html5 } # default Haml format is :xhtml
136
137 get '/' do
138 haml :index, :haml_options => {:format => :html4 } # overridden
139 end
140
141
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
142 === Erb Templates
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
143
801163e @bmizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
144 ## You'll need to require erb in your app
145 require 'erb'
146
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
147 get '/' do
148 erb :index
149 end
150
151 Renders <tt>./views/index.erb</tt>
152
7c5d693 @sr Doc for erubis
sr authored
153 === Erubis
154
84f2e0c @jstewart Correction to erubis template rendering instructions
jstewart authored
155 The erubis gem/library is required to render erubis templates:
7c5d693 @sr Doc for erubis
sr authored
156
157 ## You'll need to require erubis in your app
158 require 'erubis'
159
160 get '/' do
161 erubis :index
162 end
163
164 Renders <tt>./views/index.erubis</tt>
165
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
166 === Builder Templates
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
167
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
168 The builder gem/library is required to render builder templates:
df800b5 Docs are started
Blake Mizerany authored
169
801163e @bmizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
170 ## You'll need to require builder in your app
171 require 'builder'
172
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
173 get '/' do
174 content_type 'application/xml', :charset => 'utf-8'
175 builder :index
176 end
177
178 Renders <tt>./views/index.builder</tt>.
179
180 === Sass Templates
181
182 The sass gem/library is required to render Sass templates:
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
183
801163e @bmizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
184 ## You'll need to require haml or sass in your app
185 require 'sass'
186
4144ac1 @nmeans Added Sass information to documentation.
nmeans authored
187 get '/stylesheet.css' do
ccc19b0 @rtomayko content_type response helper with mime type lookup and parameter supp…
rtomayko authored
188 content_type 'text/css', :charset => 'utf-8'
4144ac1 @nmeans Added Sass information to documentation.
nmeans authored
189 sass :stylesheet
190 end
191
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
192 Renders <tt>./views/stylesheet.sass</tt>.
193
0321ada @dougireton In README docs, fix links to HAML and SASS Options pages.
dougireton authored
194 {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
195 can be set globally through Sinatra's configurations,
196 see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
197 and overridden on an individual basis.
198
199 set :sass, {:style => :compact } # default Sass style is :nested
200
201 get '/stylesheet.css' do
202 content_type 'text/css', :charset => 'utf-8'
b90d00c @sr Update sass example re. options
sr authored
203 sass :stylesheet, :style => :expanded # overridden
d359dc9 @kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
204 end
205
621bfcb @Ptico Added Less support
Ptico authored
206 === Less Templates
207
208 The less gem/library is required to render Less templates:
209
210 ## You'll need to require less in your app
211 require 'less'
212
213 get '/stylesheet.css' do
214 content_type 'text/css', :charset => 'utf-8'
215 less :stylesheet
216 end
217
218 Renders <tt>./views/stylesheet.less</tt>.
219
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
220 === Inline Templates
df800b5 Docs are started
Blake Mizerany authored
221
222 get '/' do
223 haml '%div.title Hello World'
224 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
225
226 Renders the inlined template string.
df800b5 Docs are started
Blake Mizerany authored
227
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
228 === Accessing Variables in Templates
df800b5 Docs are started
Blake Mizerany authored
229
5018264 @rtomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
230 Templates are evaluated within the same context as route handlers. Instance
231 variables set in route handlers are direcly accessible by templates:
df800b5 Docs are started
Blake Mizerany authored
232
233 get '/:id' do
234 @foo = Foo.find(params[:id])
95aca76 @bleything fix documentation of variable interpolation into templates
bleything authored
235 haml '%h1= @foo.name'
df800b5 Docs are started
Blake Mizerany authored
236 end
237
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
238 Or, specify an explicit Hash of local variables:
df800b5 Docs are started
Blake Mizerany authored
239
240 get '/:id' do
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
241 foo = Foo.find(params[:id])
95aca76 @bleything fix documentation of variable interpolation into templates
bleything authored
242 haml '%h1= foo.name', :locals => { :foo => foo }
df800b5 Docs are started
Blake Mizerany authored
243 end
244
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
245 This is typically used when rendering templates as partials from within
246 other templates.
247
3ef8eed @sr Deprecate use_in_file_templates!
sr authored
248 === Inline Templates
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
249
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
250 Templates may be defined at the end of the source file:
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
251
eec7d21 @bmizerany In-file-templates are automaticly loaded for you.
bmizerany authored
252 require 'rubygems'
253 require 'sinatra'
254
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
255 get '/' do
256 haml :index
257 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
258
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
259 __END__
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
260
f71330e @bmizerany quick doc fix
bmizerany authored
261 @@ layout
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
262 %html
263 = yield
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
264
f71330e @bmizerany quick doc fix
bmizerany authored
265 @@ index
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
266 %div.title Hello world!!!!!
267
3ef8eed @sr Deprecate use_in_file_templates!
sr authored
268 NOTE: Inline templates defined in the source file that requires sinatra
269 are automatically loaded. Call `enable :inline_templates` explicitly if you
270 have inline templates in other source files.
eec7d21 @bmizerany In-file-templates are automaticly loaded for you.
bmizerany authored
271
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
272 === Named Templates
273
5018264 @rtomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
274 Templates may also be defined using the top-level <tt>template</tt> method:
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
275
276 template :layout do
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
277 "%html\n =yield\n"
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
278 end
279
280 template :index do
281 '%div.title Hello World!'
282 end
283
284 get '/' do
285 haml :index
286 end
287
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
288 If a template named "layout" exists, it will be used each time a template
289 is rendered. You can disable layouts by passing <tt>:layout => false</tt>.
578bbab @djanowski Updating README for :layout => true.
djanowski authored
290
291 get '/' do
292 haml :index, :layout => !request.xhr?
293 end
294
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
295 == Helpers
df800b5 Docs are started
Blake Mizerany authored
296
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
297 Use the top-level <tt>helpers</tt> method to define helper methods for use in
5018264 @rtomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
298 route handlers and templates:
df800b5 Docs are started
Blake Mizerany authored
299
300 helpers do
301 def bar(name)
302 "#{name}bar"
303 end
304 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
305
1776a80 Added Version and Docs
Blake Mizerany authored
306 get '/:name' do
307 bar(params[:name])
308 end
df800b5 Docs are started
Blake Mizerany authored
309
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
310 == Filters
df800b5 Docs are started
Blake Mizerany authored
311
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
312 Before filters are evaluated before each request within the context of the
313 request and can modify the request and response. Instance variables set in
5018264 @rtomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
314 filters are accessible by routes and templates:
1776a80 Added Version and Docs
Blake Mizerany authored
315
df800b5 Docs are started
Blake Mizerany authored
316 before do
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
317 @note = 'Hi!'
318 request.path_info = '/foo/bar/baz'
319 end
320
321 get '/foo/*' do
322 @note #=> 'Hi!'
323 params[:splat] #=> 'bar/baz'
df800b5 Docs are started
Blake Mizerany authored
324 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
325
4e50ddb @jschementi Adds after filters
jschementi authored
326 After filter are evaluated after each request within the context of the
03dcff7 @rtomayko Typo in README
rtomayko authored
327 request and can also modify the request and response. Instance variables
4e50ddb @jschementi Adds after filters
jschementi authored
328 set in before filters and routes are accessible by after filters:
329
330 after do
331 puts response.status
332 end
333
da047d3 @rkh add pattern matching to before/after filters.
rkh authored
334 Filters optionally taking a pattern, causing them to be evaluated only if the request
335 path matches that pattern:
336
337 before '/protected/*' do
338 authenticate!
339 end
340
341 after '/create/:slug' do |slug|
342 session[:last_slug] = slug
343 end
344
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
345 == Halting
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
346
4e50ddb @jschementi Adds after filters
jschementi authored
347 To immediately stop a request within a filter or route use:
df800b5 Docs are started
Blake Mizerany authored
348
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
349 halt
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
350
fbbd822 @sr More 'halt' doc
sr authored
351 You can also specify the status when halting ...
352
353 halt 410
354
355 Or the body ...
df800b5 Docs are started
Blake Mizerany authored
356
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
357 halt 'this will be the body'
df800b5 Docs are started
Blake Mizerany authored
358
fbbd822 @sr More 'halt' doc
sr authored
359 Or both ...
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
360
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
361 halt 401, 'go away!'
df800b5 Docs are started
Blake Mizerany authored
362
fbbd822 @sr More 'halt' doc
sr authored
363 With headers ...
364
365 halt 402, {'Content-Type' => 'text/plain'}, 'revenge'
366
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
367 == Passing
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
368
5018264 @rtomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
369 A route can punt processing to the next matching route using <tt>pass</tt>:
df800b5 Docs are started
Blake Mizerany authored
370
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
371 get '/guess/:who' do
372 pass unless params[:who] == 'Frank'
6c9488e @sr Stick to single quote; kill a blank line
sr authored
373 'You got me!'
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
374 end
375
376 get '/guess/*' do
6c9488e @sr Stick to single quote; kill a blank line
sr authored
377 'You missed!'
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
378 end
379
380 The route block is immediately exited and control continues with the next
381 matching route. If no matching route is found, a 404 is returned.
df800b5 Docs are started
Blake Mizerany authored
382
13fc79d @rtomayko Remove support for source file reloading [#166]
rtomayko authored
383 == Configuration
1776a80 Added Version and Docs
Blake Mizerany authored
384
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
385 Run once, at startup, in any environment:
1776a80 Added Version and Docs
Blake Mizerany authored
386
387 configure do
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
388 ...
1776a80 Added Version and Docs
Blake Mizerany authored
389 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
390
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
391 Run only when the environment (RACK_ENV environment variable) is set to
13fc79d @rtomayko Remove support for source file reloading [#166]
rtomayko authored
392 <tt>:production</tt>:
1776a80 Added Version and Docs
Blake Mizerany authored
393
394 configure :production do
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
395 ...
1776a80 Added Version and Docs
Blake Mizerany authored
396 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
397
13fc79d @rtomayko Remove support for source file reloading [#166]
rtomayko authored
398 Run when the environment is set to either <tt>:production</tt> or
399 <tt>:test</tt>:
1776a80 Added Version and Docs
Blake Mizerany authored
400
401 configure :production, :test do
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
402 ...
1776a80 Added Version and Docs
Blake Mizerany authored
403 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
404
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
405 == Error handling
1776a80 Added Version and Docs
Blake Mizerany authored
406
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
407 Error handlers run within the same context as routes and before filters, which
408 means you get all the goodies it has to offer, like <tt>haml</tt>, <tt>erb</tt>,
409 <tt>halt</tt>, etc.
1776a80 Added Version and Docs
Blake Mizerany authored
410
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
411 === Not Found
1776a80 Added Version and Docs
Blake Mizerany authored
412
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
413 When a <tt>Sinatra::NotFound</tt> exception is raised, or the response's status
414 code is 404, the <tt>not_found</tt> handler is invoked:
1776a80 Added Version and Docs
Blake Mizerany authored
415
416 not_found do
417 'This is nowhere to be found'
418 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
419
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
420 === Error
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
421
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
422 The +error+ handler is invoked any time an exception is raised from a route
63fd773 @sr Small doc fix re. after filter
sr authored
423 block or a filter. The exception object can be obtained from the
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
424 <tt>sinatra.error</tt> Rack variable:
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
425
1776a80 Added Version and Docs
Blake Mizerany authored
426 error do
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
427 'Sorry there was a nasty error - ' + env['sinatra.error'].name
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
428 end
429
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
430 Custom errors:
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
431
432 error MyCustomError do
e7e0e55 @rtomayko Minor docfixes in README.rdoc
rtomayko authored
433 'So what happened was...' + request.env['sinatra.error'].message
1776a80 Added Version and Docs
Blake Mizerany authored
434 end
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
435
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
436 Then, if this happens:
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
437
438 get '/' do
439 raise MyCustomError, 'something bad'
440 end
441
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
442 You get this:
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
443
444 So what happened was... something bad
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
445
59e797e @sr Doc for error(500) { }
sr authored
446 Alternatively, you can install error handler for a status code:
447
448 error 403 do
449 'Access forbidden'
450 end
451
452 get '/secret' do
453 403
454 end
455
456 Or a range:
457
458 error 400..510 do
459 'Boom'
460 end
461
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
462 Sinatra installs special <tt>not_found</tt> and <tt>error</tt> handlers when
463 running under the development environment.
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
464
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
465 == Mime types
466
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
467 When using <tt>send_file</tt> or static files you may have mime types Sinatra
6d8b333 @sr Update README re. mime_type
sr authored
468 doesn't understand. Use +mime_type+ to register them by file extension:
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
469
6d8b333 @sr Update README re. mime_type
sr authored
470 mime_type :foo, 'text/foo'
1776a80 Added Version and Docs
Blake Mizerany authored
471
cb8fcb6 @sr Doc for content_type :foo
sr authored
472 You can also use it with the +content_type+ helper:
473
474 content_type :foo
475
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
476 == Rack Middleware
bda21f1 @rtomayko add doc on using Rack middleware to README
rtomayko authored
477
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
478 Sinatra rides on Rack[http://rack.rubyforge.org/], a minimal standard
479 interface for Ruby web frameworks. One of Rack's most interesting capabilities
480 for application developers is support for "middleware" -- components that sit
481 between the server and your application monitoring and/or manipulating the
482 HTTP request/response to provide various types of common functionality.
bda21f1 @rtomayko add doc on using Rack middleware to README
rtomayko authored
483
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
484 Sinatra makes building Rack middleware pipelines a cinch via a top-level
485 +use+ method:
bda21f1 @rtomayko add doc on using Rack middleware to README
rtomayko authored
486
487 require 'sinatra'
488 require 'my_custom_middleware'
489
490 use Rack::Lint
491 use MyCustomMiddleware
492
493 get '/hello' do
494 'Hello World'
495 end
496
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
497 The semantics of +use+ are identical to those defined for the
498 Rack::Builder[http://rack.rubyforge.org/doc/classes/Rack/Builder.html] DSL
499 (most frequently used from rackup files). For example, the +use+ method
500 accepts multiple/variable args as well as blocks:
bda21f1 @rtomayko add doc on using Rack middleware to README
rtomayko authored
501
502 use Rack::Auth::Basic do |username, password|
503 username == 'admin' && password == 'secret'
504 end
505
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
506 Rack is distributed with a variety of standard middleware for logging,
507 debugging, URL routing, authentication, and session handling. Sinatra uses
508 many of of these components automatically based on configuration so you
509 typically don't have to +use+ them explicitly.
bda21f1 @rtomayko add doc on using Rack middleware to README
rtomayko authored
510
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
511 == Testing
1776a80 Added Version and Docs
Blake Mizerany authored
512
c831278 @rtomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
513 Sinatra tests can be written using any Rack-based testing library
514 or framework. {Rack::Test}[http://gitrdoc.com/brynary/rack-test] is
515 recommended:
c00a25e @rtomayko Test framework refactoring
rtomayko authored
516
7cfe04a @jcrosby Fix for test/unit and test/spec docs
jcrosby authored
517 require 'my_sinatra_app'
c831278 @rtomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
518 require 'rack/test'
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
519
1776a80 Added Version and Docs
Blake Mizerany authored
520 class MyAppTest < Test::Unit::TestCase
c831278 @rtomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
521 include Rack::Test::Methods
522
523 def app
524 Sinatra::Application
525 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
526
2f377e2 @rtomayko Trim down Testing section in the README; link to doc site instead
rtomayko authored
527 def test_my_default
c00a25e @rtomayko Test framework refactoring
rtomayko authored
528 get '/'
c831278 @rtomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
529 assert_equal 'Hello World!', last_response.body
1776a80 Added Version and Docs
Blake Mizerany authored
530 end
10c90d5 @sr document testing with rspec
sr authored
531
2f377e2 @rtomayko Trim down Testing section in the README; link to doc site instead
rtomayko authored
532 def test_with_params
c831278 @rtomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
533 get '/meet', :name => 'Frank'
534 assert_equal 'Hello Frank!', last_response.body
10c90d5 @sr document testing with rspec
sr authored
535 end
536
2f377e2 @rtomayko Trim down Testing section in the README; link to doc site instead
rtomayko authored
537 def test_with_rack_env
c831278 @rtomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
538 get '/', {}, 'HTTP_USER_AGENT' => 'Songbird'
539 assert_equal "You're using Songbird!", last_response.body
1fb5b99 @dylanegan Bacon support
dylanegan authored
540 end
541 end
542
c831278 @rtomayko Recommend Rack::Test in README / note Sinatra::Test deprecation
rtomayko authored
543 NOTE: The built-in Sinatra::Test module and Sinatra::TestHarness class
544 are deprecated as of the 0.9.2 release.
1776a80 Added Version and Docs
Blake Mizerany authored
545
5360333 @sr Add a note about Sinatra::Base to the README
sr authored
546 == Sinatra::Base - Middleware, Libraries, and Modular Apps
547
548 Defining your app at the top-level works well for micro-apps but has
549 considerable drawbacks when building reuseable components such as Rack
550 middleware, Rails metal, simple libraries with a server component, or
551 even Sinatra extensions. The top-level DSL pollutes the Object namespace
552 and assumes a micro-app style configuration (e.g., a single application
553 file, ./public and ./views directories, logging, exception detail page,
554 etc.). That's where Sinatra::Base comes into play:
555
556 require 'sinatra/base'
557
558 class MyApp < Sinatra::Base
559 set :sessions, true
560 set :foo, 'bar'
561
562 get '/' do
563 'Hello world!'
564 end
565 end
566
567 The MyApp class is an independent Rack component that can act as
568 Rack middleware, a Rack application, or Rails metal. You can +use+ or
569 +run+ this class from a rackup +config.ru+ file; or, control a server
570 component shipped as a library:
571
572 MyApp.run! :host => 'localhost', :port => 9090
573
574 The methods available to Sinatra::Base subclasses are exactly as those
575 available via the top-level DSL. Most top-level apps can be converted to
576 Sinatra::Base components with two modifications:
577
578 * Your file should require +sinatra/base+ instead of +sinatra+;
579 otherwise, all of Sinatra's DSL methods are imported into the main
580 namespace.
581 * Put your app's routes, error handlers, filters, and options in a subclass
582 of Sinatra::Base.
583
584 +Sinatra::Base+ is a blank slate. Most options are disabled by default,
585 including the built-in server. See {Options and Configuration}[http://sinatra.github.com/configuration.html]
586 for details on available options and their behavior.
587
588 SIDEBAR: Sinatra's top-level DSL is implemented using a simple delegation
589 system. The +Sinatra::Application+ class -- a special subclass of
590 Sinatra::Base -- receives all :get, :put, :post, :delete, :before,
591 :error, :not_found, :configure, and :set messages sent to the
592 top-level. Have a look at the code for yourself: here's the
035fe47 @sr fix Delegator links in README
sr authored
593 {Sinatra::Delegator mixin}[http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/base.rb#L1128]
594 being {included into the main namespace}[http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/main.rb#L28]
5360333 @sr Add a note about Sinatra::Base to the README
sr authored
595
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
596 == Command line
1776a80 Added Version and Docs
Blake Mizerany authored
597
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
598 Sinatra applications can be run directly:
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
599
4d61607 @sr update README/CHANGES re. -o
sr authored
600 ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER]
1776a80 Added Version and Docs
Blake Mizerany authored
601
602 Options are:
603
604 -h # help
605 -p # set the port (default is 4567)
4d61607 @sr update README/CHANGES re. -o
sr authored
606 -o # set the host (default is 0.0.0.0)
1776a80 Added Version and Docs
Blake Mizerany authored
607 -e # set the environment (default is development)
f29486b @karmi Note "-s" (server) command line option in README
karmi authored
608 -s # specify rack server/handler (default is thin)
e7e0e55 @rtomayko Minor docfixes in README.rdoc
rtomayko authored
609 -x # turn on the mutex lock (default is off)
1776a80 Added Version and Docs
Blake Mizerany authored
610
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
611 == The Bleeding Edge
6326809 @cypher Add a subsection about tools needed for Sinatra to the Contributing s…
cypher authored
612
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
613 If you would like to use Sinatra's latest bleeding code, create a local
614 clone and run your app with the <tt>sinatra/lib</tt> directory on the
615 <tt>LOAD_PATH</tt>:
6326809 @cypher Add a subsection about tools needed for Sinatra to the Contributing s…
cypher authored
616
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
617 cd myapp
ba92616 @bmizerany Updated README to point to github.com/sinatra/sinatra.git
bmizerany authored
618 git clone git://github.com/sinatra/sinatra.git
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
619 ruby -Isinatra/lib myapp.rb
480fbfa @rtomayko minor formatting tweaks to cypher's README updates
rtomayko authored
620
4f30c1c fix unclosed <tt> in README
Mathew Cucuzella authored
621 Alternatively, you can add the <tt>sinatra/lib</tt> directory to the
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
622 <tt>LOAD_PATH</tt> in your application:
1776a80 Added Version and Docs
Blake Mizerany authored
623
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
624 $LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib'
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
625 require 'rubygems'
1776a80 Added Version and Docs
Blake Mizerany authored
626 require 'sinatra'
627
628 get '/about' do
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
629 "I'm running version " + Sinatra::VERSION
1776a80 Added Version and Docs
Blake Mizerany authored
630 end
e6c5471 @cypher Add a community section with info about the mailing list and irc channel
cypher authored
631
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
632 To update the Sinatra sources in the future:
d8fec16 @cypher Add subsection about contributing a patch as well as a link to the is…
cypher authored
633
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
634 cd myproject/sinatra
635 git pull
e6c5471 @cypher Add a community section with info about the mailing list and irc channel
cypher authored
636
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
637 == More
e6c5471 @cypher Add a community section with info about the mailing list and irc channel
cypher authored
638
754f116 @rtomayko README: better links to project website and mailing list
rtomayko authored
639 * {Project Website}[http://www.sinatrarb.com/] - Additional documentation,
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
640 news, and links to other resources.
754f116 @rtomayko README: better links to project website and mailing list
rtomayko authored
641 * {Contributing}[http://www.sinatrarb.com/contributing] - Find a bug? Need
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
642 help? Have a patch?
643 * {Lighthouse}[http://sinatra.lighthouseapp.com] - Issue tracking and release
644 planning.
5018264 @rtomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
645 * {Twitter}[http://twitter.com/sinatra]
754f116 @rtomayko README: better links to project website and mailing list
rtomayko authored
646 * {Mailing List}[http://groups.google.com/group/sinatrarb/topics]
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
647 * {IRC: #sinatra}[irc://chat.freenode.net/#sinatra] on http://freenode.net
Something went wrong with that request. Please try again.