Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 2015 lines (1419 sloc) 58.824 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'
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger 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
63a1bb3 Konstantin Haase mention thin in readme
rkh authored
20 It is recommended to also run <tt>gem install thin</tt>, which Sinatra will
21 pick up if available.
22
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
23 == Routes
24
73e137d Konstantin Haase improve language in readme
rkh authored
25 In Sinatra, a route is an HTTP method paired with a URL-matching pattern.
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
26 Each route is associated with a block:
df800b5 Docs are started
Blake Mizerany authored
27
28 get '/' do
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
29 .. show something ..
df800b5 Docs are started
Blake Mizerany authored
30 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
31
df800b5 Docs are started
Blake Mizerany authored
32 post '/' do
33 .. create something ..
34 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
35
df800b5 Docs are started
Blake Mizerany authored
36 put '/' do
59381b5 Konstantin Haase mind readme and changes
rkh authored
37 .. replace something ..
38 end
39
40 patch '/' do
41 .. modify something ..
df800b5 Docs are started
Blake Mizerany authored
42 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
43
df800b5 Docs are started
Blake Mizerany authored
44 delete '/' do
45 .. annihilate something ..
46 end
59381b5 Konstantin Haase mind readme and changes
rkh authored
47
ba1fd4c Jamie Murai Updated README.rdoc to reflect added OPTIONS request type.
jammur authored
48 options '/' do
49 .. appease something ..
50 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
51
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
52 Routes are matched in the order they are defined. The first route that
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
53 matches the request is invoked.
1776a80 Added Version and Docs
Blake Mizerany authored
54
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
55 Route patterns may include named parameters, accessible via the
56 <tt>params</tt> hash:
1776a80 Added Version and Docs
Blake Mizerany authored
57
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
58 get '/hello/:name' do
ce0fe87 Scott Johnson fix inaccurate comment in README
scottj97 authored
59 # matches "GET /hello/foo" and "GET /hello/bar"
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
60 # params[:name] is 'foo' or 'bar'
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
61 "Hello #{params[:name]}!"
1776a80 Added Version and Docs
Blake Mizerany authored
62 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
63
6569d1b Brandon Dimcheff Added route block params in routing statements [#140]
bdimcheff authored
64 You can also access named parameters via block parameters:
65
66 get '/hello/:name' do |n|
67 "Hello #{n}!"
68 end
69
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
70 Route patterns may also include splat (or wildcard) parameters, accessible
b9d49cf burningTyger Readme[.de].rdoc update
burningTyger authored
71 via the <tt>params[:splat]</tt> array:
1776a80 Added Version and Docs
Blake Mizerany authored
72
9c85e99 Victor Hugo Borja Specs, documentation and fixes for splat'n routes
vic authored
73 get '/say/*/to/*' do
74 # matches /say/hello/to/world
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
75 params[:splat] # => ["hello", "world"]
9c85e99 Victor Hugo Borja Specs, documentation and fixes for splat'n routes
vic authored
76 end
77
78 get '/download/*.*' do
79 # matches /download/path/to/file.xml
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
80 params[:splat] # => ["path/to/file", "xml"]
1776a80 Added Version and Docs
Blake Mizerany authored
81 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
82
4ea9980 Takanori Ishikawa Added wildcard pattern with block parameters in README
ishikawa authored
83 Or with block parameters:
84
85 get '/download/*.*' do |path, ext|
86 [path, ext] # => ["path/to/file", "xml"]
87 end
88
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
89 Route matching with Regular Expressions:
90
91 get %r{/hello/([\w]+)} do
92 "Hello, #{params[:captures].first}!"
93 end
94
6569d1b Brandon Dimcheff Added route block params in routing statements [#140]
bdimcheff authored
95 Or with a block parameter:
96
97 get %r{/hello/([\w]+)} do |c|
98 "Hello, #{c}!"
99 end
100
f5b1de9 Alessandro Dal Grande Added optional parameter info to the README
aledalgrande authored
101 Route patterns may have optional parameters:
102
103 get '/posts.?:format?' do
104 # matches "GET /posts" and any extension "GET /posts.json", "GET /posts.xml" etc.
105 end
106
1f1e58e Konstantin Haase add rack-protection, fixes #310
rkh authored
107 By the way, unless you disable the path traversal attack protection (see below),
108 the request path might be modified before matching against your routes.
109
726feeb Konstantin Haase Documentation for condition. Fixes GH #15.
rkh authored
110 === Conditions
111
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
112 Routes may include a variety of matching conditions, such as the user agent:
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
113
1776a80 Added Version and Docs
Blake Mizerany authored
114 get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
115 "You're using Songbird version #{params[:agent][0]}"
116 end
117
118 get '/foo' do
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
119 # Matches non-songbird browsers
1776a80 Added Version and Docs
Blake Mizerany authored
120 end
df800b5 Docs are started
Blake Mizerany authored
121
fa52709 Konstantin Haase fix markup for inline code in README
rkh authored
122 Other available conditions are +host_name+ and +provides+:
726feeb Konstantin Haase Documentation for condition. Fixes GH #15.
rkh authored
123
124 get '/', :host_name => /^admin\./ do
125 "Admin Area, Access denied!"
126 end
127
128 get '/', :provides => 'html' do
129 haml :index
130 end
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
131
726feeb Konstantin Haase Documentation for condition. Fixes GH #15.
rkh authored
132 get '/', :provides => ['rss', 'atom', 'xml'] do
133 builder :feed
134 end
135
136 You can easily define your own conditions:
137
138 set(:probability) { |value| condition { rand <= value } }
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
139
726feeb Konstantin Haase Documentation for condition. Fixes GH #15.
rkh authored
140 get '/win_a_car', :probability => 0.1 do
141 "You won!"
142 end
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
143
726feeb Konstantin Haase Documentation for condition. Fixes GH #15.
rkh authored
144 get '/win_a_car' do
145 "Sorry, you lost."
146 end
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
147
8b5fcf4 Iain Barnett added example for condition with array argument
yb66 authored
148 For a condition that takes multiple values use a splat:
149
150 set(:auth) do |*roles| # <- notice the splat here
151 condition do
152 unless logged_in? && roles.any? {|role| current_user.in_role? role }
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
153 redirect "/login/", 303
8b5fcf4 Iain Barnett added example for condition with array argument
yb66 authored
154 end
155 end
156 end
726feeb Konstantin Haase Documentation for condition. Fixes GH #15.
rkh authored
157
8b5fcf4 Iain Barnett added example for condition with array argument
yb66 authored
158 get "/my/account/", :auth => [:user, :admin] do
159 "Your Account Details"
160 end
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
161
8b5fcf4 Iain Barnett added example for condition with array argument
yb66 authored
162 get "/only/admin/", :auth => :admin do
163 "Only admins are allowed here!"
164 end
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
165
a64d082 Konstantin Haase capitalize heading
rkh authored
166 === Return Values
aaeb564 Konstantin Haase document route return values, fixes GH #23
rkh authored
167
168 The return value of a route block determines at least the response body passed
169 on to the HTTP client, or at least the next middleware in the Rack stack.
73e137d Konstantin Haase improve language in readme
rkh authored
170 Most commonly, this is a string, as in the above examples. But other values are
aaeb564 Konstantin Haase document route return values, fixes GH #23
rkh authored
171 also accepted.
172
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
173 You can return any object that would either be a valid Rack response, Rack
174 body object or HTTP status code:
aaeb564 Konstantin Haase document route return values, fixes GH #23
rkh authored
175
210e342 burningTyger fix some typos in README.rdoc
burningTyger authored
176 * An Array with three elements: <tt>[status (Fixnum), headers (Hash), response
177 body (responds to #each)]</tt>
178 * An Array with two elements: <tt>[status (Fixnum), response body (responds to
179 #each)]</tt>
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
180 * An object that responds to <tt>#each</tt> and passes nothing but strings to
210e342 burningTyger fix some typos in README.rdoc
burningTyger authored
181 the given block
aaeb564 Konstantin Haase document route return values, fixes GH #23
rkh authored
182 * A Fixnum representing the status code
183
73e137d Konstantin Haase improve language in readme
rkh authored
184 That way we can, for instance, easily implement a streaming example:
aaeb564 Konstantin Haase document route return values, fixes GH #23
rkh authored
185
186 class Stream
187 def each
188 100.times { |i| yield "#{i}\n" }
189 end
190 end
191
8fbd9c2 Konstantin Haase Simplify streaming example.
rkh authored
192 get('/') { Stream.new }
aaeb564 Konstantin Haase document route return values, fixes GH #23
rkh authored
193
49d4c90 Konstantin Haase add #stream helper
rkh authored
194 You can also use the +stream+ helper method (described below) to reduce boiler
195 plate and embed the streaming logic in the route.
196
7ec4039 Konstantin Haase document custom route matchers
rkh authored
197 === Custom Route Matchers
198
199 As shown above, Sinatra ships with built-in support for using String patterns
200 and regular expressions as route matches. However, it does not stop there. You
201 can easily define your own matchers:
202
203 class AllButPattern
204 Match = Struct.new(:captures)
205
206 def initialize(except)
207 @except = except
9c03711 Konstantin Haase typo
rkh authored
208 @captures = Match.new([])
7ec4039 Konstantin Haase document custom route matchers
rkh authored
209 end
210
211 def match(str)
9c03711 Konstantin Haase typo
rkh authored
212 @captures unless @except === str
7ec4039 Konstantin Haase document custom route matchers
rkh authored
213 end
214 end
215
216 def all_but(pattern)
217 AllButPattern.new(pattern)
218 end
219
220 get all_but("/index") do
221 # ...
222 end
223
224 Note that the above example might be over-engineered, as it can also be
225 expressed as:
226
227 get // do
228 pass if request.path_info == "/index"
229 # ...
230 end
231
232 Or, using negative look ahead:
233
234 get %r{^(?!/index$)} do
235 # ...
236 end
237
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
238 == Static Files
047edc6 update README with Static help
Blake Mizerany authored
239
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
240 Static files are served from the <tt>./public</tt> directory. You can specify
d1ab58d Konstantin Haase rename public to public_folder, fixes #301
rkh authored
241 a different location by setting the <tt>:public_folder</tt> option:
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
242
d1ab58d Konstantin Haase rename public to public_folder, fixes #301
rkh authored
243 set :public_folder, File.dirname(__FILE__) + '/static'
df800b5 Docs are started
Blake Mizerany authored
244
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
245 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
246 <tt>./public/css/style.css</tt> is made available as
247 <tt>http://example.com/css/style.css</tt>.
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
248
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
249 Use the <tt>:static_cache_control</tt> setting (see below) to add
e2ebe0f Konstantin Haase fix markup
rkh authored
250 <tt>Cache-Control</tt> header info.
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
251
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
252 == Views / Templates
df800b5 Docs are started
Blake Mizerany authored
253
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
254 Each template language is exposed as via its own rendering method. These
255 methods simply return a string:
06161bf Markus Prinz Note on passing template symbols vs. strings in README
cypher authored
256
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
257 get '/' do
258 erb :index
259 end
df800b5 Docs are started
Blake Mizerany authored
260
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
261 This renders <tt>views/index.erb</tt>.
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
262
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
263 Instead of a template name, you can also just pass in the template content
264 directly:
801163e Blake Mizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
265
df800b5 Docs are started
Blake Mizerany authored
266 get '/' do
c363735 eckz Fixed code typo in README
eckz authored
267 code = "<%= Time.now %>"
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
268 erb code
df800b5 Docs are started
Blake Mizerany authored
269 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
270
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
271 Templates take a second argument, the options hash:
d359dc9 Kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
272
273 get '/' do
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
274 erb :index, :layout => :post
d359dc9 Kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
275 end
276
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
277 This will render <tt>views/index.erb</tt> embedded in the
278 <tt>views/post.erb</tt> (default is <tt>views/layout.erb</tt>, if it exists).
d359dc9 Kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
279
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
280 Any options not understood by Sinatra will be passed on to the template
281 engine:
801163e Blake Mizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
282
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
283 get '/' do
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
284 haml :index, :format => :html5
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
285 end
286
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
287 You can also set options per template language in general:
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
288
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
289 set :haml, :format => :html5
801163e Blake Mizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
290
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
291 get '/' do
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
292 haml :index
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
293 end
294
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
295 Options passed to the render method override options set via +set+.
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
296
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
297 Available Options:
dd81da1 Konstantin Haase Add nokogiri helper method. Tilt supports Nokogiri for quite some time n...
rkh authored
298
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
299 [locals]
300 List of locals passed to the document. Handy with partials.
301 Example: <tt>erb "<%= foo %>", :locals => {:foo => "bar"}</tt>
dd81da1 Konstantin Haase Add nokogiri helper method. Tilt supports Nokogiri for quite some time n...
rkh authored
302
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
303 [default_encoding]
304 String encoding to use if uncertain. Defaults to
305 <tt>settings.default_encoding</tt>.
dd81da1 Konstantin Haase Add nokogiri helper method. Tilt supports Nokogiri for quite some time n...
rkh authored
306
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
307 [views]
308 Views folder to load templates from. Defaults to <tt>settings.views</tt>.
dd81da1 Konstantin Haase Add nokogiri helper method. Tilt supports Nokogiri for quite some time n...
rkh authored
309
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
310 [layout]
311 Whether to use a layout (+true+ or +false+), if it's a Symbol, specifies
6f33e1b burningTyger better :layout example - fixes #269
burningTyger authored
312 what template to use. Example: <tt>erb :index, :layout => !request.xhr?</tt>
dd81da1 Konstantin Haase Add nokogiri helper method. Tilt supports Nokogiri for quite some time n...
rkh authored
313
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
314 [content_type]
315 Content-Type the template produces, default depends on template language.
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
316
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
317 [scope]
318 Scope to render template under. Defaults to the application instance. If you
319 change this, instance variables and helper methods will not be available.
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
320
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
321 [layout_engine]
322 Template engine to use for rendering the layout. Useful for languages that
323 do not support layouts otherwise. Defaults to the engine used for the
c99fe87 Gaku Ueda it looks like a typo.
gaku authored
324 template. Example: <tt>set :rdoc, :layout_engine => :erb</tt>
801163e Blake Mizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
325
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
326 Templates are assumed to be located directly under the <tt>./views</tt>
327 directory. To use a different views directory:
4144ac1 Nickolas Means Added Sass information to documentation.
nmeans authored
328
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
329 set :views, settings.root + '/templates'
4144ac1 Nickolas Means Added Sass information to documentation.
nmeans authored
330
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
331 One important thing to remember is that you always have to reference
332 templates with symbols, even if they're in a subdirectory (in this
333 case, use <tt>:'subdir/template'</tt>). You must use a symbol because
334 otherwise rendering methods will render any strings passed to them
335 directly.
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
336
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
337 === Available Template Languages
d359dc9 Kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
338
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
339 Some languages have multiple implementations. To specify what implementation
340 to use (and to be thread-safe), you should simply require it first:
d359dc9 Kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
341
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
342 require 'rdiscount' # or require 'bluecloth'
343 get('/') { markdown :index }
d359dc9 Kematzy Merge app-level haml/sass options with call options [#184]
kematzy authored
344
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
345 === Haml Templates
cf3c218 Pedro Menezes Adding scss support through specific command
pedromenezes authored
346
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
347 Dependency:: {haml}[http://haml-lang.com/]
348 File Extensions:: <tt>.haml</tt>
349 Example:: <tt>haml :index, :format => :html5</tt>
cf3c218 Pedro Menezes Adding scss support through specific command
pedromenezes authored
350
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
351 === Erb Templates
cf3c218 Pedro Menezes Adding scss support through specific command
pedromenezes authored
352
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
353 Dependency:: {erubis}[http://www.kuwata-lab.com/erubis/] or
354 erb (included in Ruby)
355 File Extensions:: <tt>.erb</tt>, <tt>.rhtml</tt> or <tt>.erubis</tt> (Erubis
356 only)
357 Example:: <tt>erb :index</tt>
cf3c218 Pedro Menezes Adding scss support through specific command
pedromenezes authored
358
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
359 === Builder Templates
cf3c218 Pedro Menezes Adding scss support through specific command
pedromenezes authored
360
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
361 Dependency:: {builder}[http://builder.rubyforge.org/]
362 File Extensions:: <tt>.builder</tt>
363 Example:: <tt>builder { |xml| xml.em "hi" }</tt>
cf3c218 Pedro Menezes Adding scss support through specific command
pedromenezes authored
364
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
365 It also takes a block for inline templates (see example).
cf3c218 Pedro Menezes Adding scss support through specific command
pedromenezes authored
366
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
367 === Nokogiri Templates
cf3c218 Pedro Menezes Adding scss support through specific command
pedromenezes authored
368
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
369 Dependency:: {nokogiri}[http://nokogiri.org/]
370 File Extensions:: <tt>.nokogiri</tt>
f4efd43 Gabriel Andretta fix copy/paste error in readme
gnandretta authored
371 Example:: <tt>nokogiri { |xml| xml.em "hi" }</tt>
621bfcb Andriy Savchenko Added Less support
Ptico authored
372
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
373 It also takes a block for inline templates (see example).
621bfcb Andriy Savchenko Added Less support
Ptico authored
374
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
375 === Sass Templates
621bfcb Andriy Savchenko Added Less support
Ptico authored
376
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
377 Dependency:: {sass}[http://sass-lang.com/]
378 File Extensions:: <tt>.sass</tt>
379 Example:: <tt>sass :stylesheet, :style => :expanded</tt>
621bfcb Andriy Savchenko Added Less support
Ptico authored
380
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
381 === SCSS Templates
621bfcb Andriy Savchenko Added Less support
Ptico authored
382
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
383 Dependency:: {sass}[http://sass-lang.com/]
384 File Extensions:: <tt>.scss</tt>
385 Example:: <tt>scss :stylesheet, :style => :expanded</tt>
28a3a35 Konstantin Haase Add liquid helper method. Tilt supports liquid for quite some time now, ...
rkh authored
386
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
387 === Less Templates
28a3a35 Konstantin Haase Add liquid helper method. Tilt supports liquid for quite some time now, ...
rkh authored
388
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
389 Dependency:: {less}[http://www.lesscss.org/]
390 File Extensions:: <tt>.less</tt>
391 Example:: <tt>less :stylesheet</tt>
28a3a35 Konstantin Haase Add liquid helper method. Tilt supports liquid for quite some time now, ...
rkh authored
392
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
393 === Liquid Templates
28a3a35 Konstantin Haase Add liquid helper method. Tilt supports liquid for quite some time now, ...
rkh authored
394
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
395 Dependency:: {liquid}[http://www.liquidmarkup.org/]
396 File Extensions:: <tt>.liquid</tt>
397 Example:: <tt>liquid :index, :locals => { :key => 'value' }</tt>
28a3a35 Konstantin Haase Add liquid helper method. Tilt supports liquid for quite some time now, ...
rkh authored
398
399 Since you cannot call Ruby methods (except for +yield+) from a Liquid
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
400 template, you almost always want to pass locals to it.
28a3a35 Konstantin Haase Add liquid helper method. Tilt supports liquid for quite some time now, ...
rkh authored
401
970169b Konstantin Haase Add markdown helper method. Tilt supports markdown for quite some time n...
rkh authored
402 === Markdown Templates
403
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
404 Dependency:: {rdiscount}[https://github.com/rtomayko/rdiscount],
405 {redcarpet}[https://github.com/tanoku/redcarpet],
406 {bluecloth}[http://deveiate.org/projects/BlueCloth],
407 {kramdown}[http://kramdown.rubyforge.org/] *or*
408 {maruku}[http://maruku.rubyforge.org/]
409 File Extensions:: <tt>.markdown</tt>, <tt>.mkd</tt> and <tt>.md</tt>
410 Example:: <tt>markdown :index, :layout_engine => :erb</tt>
970169b Konstantin Haase Add markdown helper method. Tilt supports markdown for quite some time n...
rkh authored
411
a743c7d Konstantin Haase Add BlueCloth example to README.
rkh authored
412 It is not possible to call methods from markdown, nor to pass locals to it.
413 You therefore will usually use it in combination with another rendering
414 engine:
970169b Konstantin Haase Add markdown helper method. Tilt supports markdown for quite some time n...
rkh authored
415
416 erb :overview, :locals => { :text => markdown(:introduction) }
417
a743c7d Konstantin Haase Add BlueCloth example to README.
rkh authored
418 Note that you may also call the +markdown+ method from within other templates:
970169b Konstantin Haase Add markdown helper method. Tilt supports markdown for quite some time n...
rkh authored
419
420 %h1 Hello From Haml!
421 %p= markdown(:greetings)
422
a0f4717 Konstantin Haase Explain how to use :layout_engine in README.
rkh authored
423 Since you cannot call Ruby from Markdown, you cannot use layouts written in
424 Markdown. However, it is possible to use another rendering engine for the
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
425 template than for the layout by passing the <tt>:layout_engine</tt> option.
a743c7d Konstantin Haase Add BlueCloth example to README.
rkh authored
426
b464e02 Konstantin Haase Add textile helper method. Tilt supports textile for quite some time now...
rkh authored
427 === Textile Templates
428
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
429 Dependency:: {RedCloth}[http://redcloth.org/]
430 File Extensions:: <tt>.textile</tt>
431 Example:: <tt>textile :index, :layout_engine => :erb</tt>
b464e02 Konstantin Haase Add textile helper method. Tilt supports textile for quite some time now...
rkh authored
432
a743c7d Konstantin Haase Add BlueCloth example to README.
rkh authored
433 It is not possible to call methods from textile, nor to pass locals to it. You
434 therefore will usually use it in combination with another rendering engine:
b464e02 Konstantin Haase Add textile helper method. Tilt supports textile for quite some time now...
rkh authored
435
436 erb :overview, :locals => { :text => textile(:introduction) }
437
9fc3f1d Konstantin Haase README formatting adjustments
rkh authored
438 Note that you may also call the +textile+ method from within other templates:
b464e02 Konstantin Haase Add textile helper method. Tilt supports textile for quite some time now...
rkh authored
439
440 %h1 Hello From Haml!
441 %p= textile(:greetings)
442
a0f4717 Konstantin Haase Explain how to use :layout_engine in README.
rkh authored
443 Since you cannot call Ruby from Textile, you cannot use layouts written in
444 Textile. However, it is possible to use another rendering engine for the
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
445 template than for the layout by passing the <tt>:layout_engine</tt> option.
a0f4717 Konstantin Haase Explain how to use :layout_engine in README.
rkh authored
446
c248dba Konstantin Haase Add rdoc helper method. Tilt supports RDoc for quite some time now, but ...
rkh authored
447 === RDoc Templates
448
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
449 Dependency:: {rdoc}[http://rdoc.rubyforge.org/]
450 File Extensions:: <tt>.rdoc</tt>
2bd43c0 Gaku Ueda Fixed a copy-paste error.
gaku authored
451 Example:: <tt>rdoc :README, :layout_engine => :erb</tt>
c248dba Konstantin Haase Add rdoc helper method. Tilt supports RDoc for quite some time now, but ...
rkh authored
452
a743c7d Konstantin Haase Add BlueCloth example to README.
rkh authored
453 It is not possible to call methods from rdoc, nor to pass locals to it. You
454 therefore will usually use it in combination with another rendering engine:
c248dba Konstantin Haase Add rdoc helper method. Tilt supports RDoc for quite some time now, but ...
rkh authored
455
456 erb :overview, :locals => { :text => rdoc(:introduction) }
457
9fc3f1d Konstantin Haase README formatting adjustments
rkh authored
458 Note that you may also call the +rdoc+ method from within other templates:
c248dba Konstantin Haase Add rdoc helper method. Tilt supports RDoc for quite some time now, but ...
rkh authored
459
460 %h1 Hello From Haml!
461 %p= rdoc(:greetings)
462
a0f4717 Konstantin Haase Explain how to use :layout_engine in README.
rkh authored
463 Since you cannot call Ruby from RDoc, you cannot use layouts written in
464 RDoc. However, it is possible to use another rendering engine for the
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
465 template than for the layout by passing the <tt>:layout_engine</tt> option.
a0f4717 Konstantin Haase Explain how to use :layout_engine in README.
rkh authored
466
7cb94f2 Konstantin Haase Add radius helper method. Tilt supports radius for quite some time now, ...
rkh authored
467 === Radius Templates
468
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
469 Dependency:: {radius}[http://radius.rubyforge.org/]
470 File Extensions:: <tt>.radius</tt>
471 Example:: <tt>radius :index, :locals => { :key => 'value' }</tt>
7cb94f2 Konstantin Haase Add radius helper method. Tilt supports radius for quite some time now, ...
rkh authored
472
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
473 Since you cannot call Ruby methods directly from a Radius template, you almost
474 always want to pass locals to it.
7cb94f2 Konstantin Haase Add radius helper method. Tilt supports radius for quite some time now, ...
rkh authored
475
8ce74b3 Konstantin Haase Add markaby helper method. Tilt supports Markaby for quite some time now...
rkh authored
476 === Markaby Templates
477
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
478 Dependency:: {markaby}[http://markaby.github.com/]
479 File Extensions:: <tt>.mab</tt>
480 Example:: <tt>markaby { h1 "Welcome!" }</tt>
8ce74b3 Konstantin Haase Add markaby helper method. Tilt supports Markaby for quite some time now...
rkh authored
481
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
482 It also takes a block for inline templates (see example).
0ff41a6 Konstantin Haase Add support for passing a block to the markaby method:
rkh authored
483
ca7fbe5 Konstantin Haase Add documentation for Slim templates.
rkh authored
484 === Slim Templates
485
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
486 Dependency:: {slim}[http://slim-lang.com/]
487 File Extensions:: <tt>.slim</tt>
488 Example:: <tt>slim :index</tt>
ca7fbe5 Konstantin Haase Add documentation for Slim templates.
rkh authored
489
9ce9e54 Konstantin Haase add support for creole templates
rkh authored
490 === Creole Templates
491
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
492 Dependency:: {creole}[https://github.com/minad/creole]
493 File Extensions:: <tt>.creole</tt>
494 Example:: <tt>creole :wiki, :layout_engine => :erb</tt>
f58d015 Konstantin Haase Add coffee helper method. Tilt supports CoffeeScript again, but it was n...
rkh authored
495
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
496 It is not possible to call methods from creole, nor to pass locals to it. You
497 therefore will usually use it in combination with another rendering engine:
de11b44 Konstantin Haase Update CoffeeScript section with requirements for ruby-coffee-script 2.x...
rkh authored
498
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
499 erb :overview, :locals => { :text => creole(:introduction) }
de11b44 Konstantin Haase Update CoffeeScript section with requirements for ruby-coffee-script 2.x...
rkh authored
500
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
501 Note that you may also call the +creole+ method from within other templates:
de11b44 Konstantin Haase Update CoffeeScript section with requirements for ruby-coffee-script 2.x...
rkh authored
502
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
503 %h1 Hello From Haml!
504 %p= creole(:greetings)
f58d015 Konstantin Haase Add coffee helper method. Tilt supports CoffeeScript again, but it was n...
rkh authored
505
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
506 Since you cannot call Ruby from Creole, you cannot use layouts written in
507 Creole. However, it is possible to use another rendering engine for the
508 template than for the layout by passing the <tt>:layout_engine</tt> option.
f58d015 Konstantin Haase Add coffee helper method. Tilt supports CoffeeScript again, but it was n...
rkh authored
509
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
510 === CoffeeScript Templates
f58d015 Konstantin Haase Add coffee helper method. Tilt supports CoffeeScript again, but it was n...
rkh authored
511
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
512 Dependency:: {coffee-script}[https://github.com/josh/ruby-coffee-script]
513 and a {way to execute javascript}[https://github.com/sstephenson/execjs/blob/master/README.md#readme]
514 File Extensions:: <tt>.coffee</tt>
515 Example:: <tt>coffee :index</tt>
f58d015 Konstantin Haase Add coffee helper method. Tilt supports CoffeeScript again, but it was n...
rkh authored
516
d255666 Jamie Hodge add support for yajl templates, merges #450
jamiehodge authored
517 === Yajl Templates
518
519 Dependency:: {yajl-ruby}[https://github.com/brianmario/yajl-ruby]
520 File Extensions:: <tt>.yajl</tt>
521 Example:: <tt>yajl :index, :locals => { :key => 'qux' }, :callback => 'present', :variable => 'resource' </tt>
522
523 The template source is evaluated as a Ruby string, and the resulting json variable is converted #to_json.
524
525 json = { :foo => 'bar' }
526 json[:baz] = key
527
528 The <tt>:callback</tt> and <tt>:variable</tt> options can be used to decorate the rendered object.
529
530 var resource = {"foo":"bar","baz":"qux"}; present(resource);
531
705c93f Konstantin Haase Rename one of the two 'Inline Templates' sections to 'Embedded Templates...
rkh authored
532 === Embedded Templates
df800b5 Docs are started
Blake Mizerany authored
533
534 get '/' do
535 haml '%div.title Hello World'
536 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
537
705c93f Konstantin Haase Rename one of the two 'Inline Templates' sections to 'Embedded Templates...
rkh authored
538 Renders the embedded template string.
df800b5 Docs are started
Blake Mizerany authored
539
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
540 === Accessing Variables in Templates
df800b5 Docs are started
Blake Mizerany authored
541
5018264 Ryan Tomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
542 Templates are evaluated within the same context as route handlers. Instance
4a659e1 burningTyger fixed some typos et al in the README
burningTyger authored
543 variables set in route handlers are directly accessible by templates:
df800b5 Docs are started
Blake Mizerany authored
544
545 get '/:id' do
546 @foo = Foo.find(params[:id])
95aca76 Ben Bleything fix documentation of variable interpolation into templates
bleything authored
547 haml '%h1= @foo.name'
df800b5 Docs are started
Blake Mizerany authored
548 end
549
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
550 Or, specify an explicit Hash of local variables:
df800b5 Docs are started
Blake Mizerany authored
551
552 get '/:id' do
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
553 foo = Foo.find(params[:id])
71e5206 Emanuele Vicentini Tweaked :locals example.
baldowl authored
554 haml '%h1= bar.name', :locals => { :bar => foo }
df800b5 Docs are started
Blake Mizerany authored
555 end
556
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
557 This is typically used when rendering templates as partials from within
558 other templates.
559
3ef8eed Simon Rozet Deprecate use_in_file_templates!
sr authored
560 === Inline Templates
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
561
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
562 Templates may be defined at the end of the source file:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
563
eec7d21 Blake Mizerany In-file-templates are automaticly loaded for you.
bmizerany authored
564 require 'sinatra'
565
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
566 get '/' do
567 haml :index
568 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
569
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
570 __END__
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
571
f71330e Blake Mizerany quick doc fix
bmizerany authored
572 @@ layout
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
573 %html
574 = yield
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
575
f71330e Blake Mizerany quick doc fix
bmizerany authored
576 @@ index
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
577 %div.title Hello world.
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
578
6584711 Konstantin Haase Minor markup fix in README.
rkh authored
579 NOTE: Inline templates defined in the source file that requires sinatra are
ca624fd Konstantin Haase Fix the minor markup fix in README.
rkh authored
580 automatically loaded. Call <tt>enable :inline_templates</tt> explicitly if you
3ef8eed Simon Rozet Deprecate use_in_file_templates!
sr authored
581 have inline templates in other source files.
eec7d21 Blake Mizerany In-file-templates are automaticly loaded for you.
bmizerany authored
582
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
583 === Named Templates
584
5018264 Ryan Tomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
585 Templates may also be defined using the top-level <tt>template</tt> method:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
586
587 template :layout do
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
588 "%html\n =yield\n"
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
589 end
590
591 template :index do
592 '%div.title Hello World!'
593 end
594
595 get '/' do
596 haml :index
597 end
598
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
599 If a template named "layout" exists, it will be used each time a template
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
600 is rendered. You can individually disable layouts by passing
601 <tt>:layout => false</tt> or disable them by default via
210e342 burningTyger fix some typos in README.rdoc
burningTyger authored
602 <tt>set :haml, :layout => false</tt>:
578bbab Damian Janowski Updating README for :layout => true.
djanowski authored
603
604 get '/' do
605 haml :index, :layout => !request.xhr?
606 end
607
d7aa6a3 Konstantin Haase Add 'Associating File Extensions' section to README.
rkh authored
608 === Associating File Extensions
609
610 To associate a file extension with a template engine, use
611 <tt>Tilt.register</tt>. For instance, if you like to use the file extension
612 +tt+ for Textile templates, you can do the following:
613
614 Tilt.register :tt, Tilt[:textile]
615
4a659e1 burningTyger fixed some typos et al in the README
burningTyger authored
616 === Adding Your Own Template Engine
9269686 Konstantin Haase Add "Adding You Own Template Engine" section to README.
rkh authored
617
618 First, register your engine with Tilt, then create a rendering method:
619
620 Tilt.register :myat, MyAwesomeTemplateEngine
621
622 helpers do
623 def myat(*args) render(:myat, *args) end
624 end
625
626 get '/' do
627 myat :index
628 end
629
630 Renders <tt>./views/index.myat</tt>. See https://github.com/rtomayko/tilt to
631 learn more about Tilt.
632
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
633 == Filters
df800b5 Docs are started
Blake Mizerany authored
634
73e137d Konstantin Haase improve language in readme
rkh authored
635 Before filters are evaluated before each request within the same
636 context as the routes will be and can modify the request and response. Instance
637 variables set in filters are accessible by routes and templates:
1776a80 Added Version and Docs
Blake Mizerany authored
638
df800b5 Docs are started
Blake Mizerany authored
639 before do
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
640 @note = 'Hi!'
641 request.path_info = '/foo/bar/baz'
642 end
643
644 get '/foo/*' do
645 @note #=> 'Hi!'
646 params[:splat] #=> 'bar/baz'
df800b5 Docs are started
Blake Mizerany authored
647 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
648
73e137d Konstantin Haase improve language in readme
rkh authored
649 After filters are evaluated after each request within the same context and can
650 also modify the request and response. Instance variables set in before filters
651 and routes are accessible by after filters:
4e50ddb Jimmy Schementi Adds after filters
jschementi authored
652
653 after do
100baab Konstantin Haase typo - I thought I fixed that before committing
rkh authored
654 puts response.status
4e50ddb Jimmy Schementi Adds after filters
jschementi authored
655 end
656
b94716c Konstantin Haase fix readme markup
rkh authored
657 Note: Unless you use the +body+ method rather than just returning a String from
380c312 Konstantin Haase Document accessing response body in after filter. Fixes #168.
rkh authored
658 the routes, the body will not yet be available in the after filter, since it is
659 generated later on.
660
73e137d Konstantin Haase improve language in readme
rkh authored
661 Filters optionally take a pattern, causing them to be evaluated only if the
662 request path matches that pattern:
da047d3 Konstantin Haase add pattern matching to before/after filters.
rkh authored
663
664 before '/protected/*' do
665 authenticate!
666 end
667
668 after '/create/:slug' do |slug|
669 session[:last_slug] = slug
670 end
671
73e137d Konstantin Haase improve language in readme
rkh authored
672 Like routes, filters also take conditions:
7a9101a Konstantin Haase Like routes, filters now also take conditions:
rkh authored
673
674 before :agent => /Songbird/ do
675 # ...
676 end
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
677
7a9101a Konstantin Haase Like routes, filters now also take conditions:
rkh authored
678 after '/blog/*', :host_name => 'example.com' do
679 # ...
680 end
681
08d5682 Konstantin Haase reorganizing helpers in readme
rkh authored
682 == Helpers
683
684 Use the top-level <tt>helpers</tt> method to define helper methods for use in
685 route handlers and templates:
686
687 helpers do
688 def bar(name)
689 "#{name}bar"
690 end
691 end
692
693 get '/:name' do
694 bar(params[:name])
695 end
696
ca06364 Konstantin Haase improve helpers documentation
rkh authored
697 Alternatively, helper methods can be separately defined in a module:
7abe19c Anurag Priyam README: show how to define helper functions in a separate `module`
yeban authored
698
699 module FooUtils
ca06364 Konstantin Haase improve helpers documentation
rkh authored
700 def foo(name) "#{name}foo" end
7abe19c Anurag Priyam README: show how to define helper functions in a separate `module`
yeban authored
701 end
702
ca06364 Konstantin Haase improve helpers documentation
rkh authored
703 module BarUtils
704 def bar(name) "#{name}bar" end
7abe19c Anurag Priyam README: show how to define helper functions in a separate `module`
yeban authored
705 end
706
ca06364 Konstantin Haase improve helpers documentation
rkh authored
707 helpers FooUtils, BarUtils
7abe19c Anurag Priyam README: show how to define helper functions in a separate `module`
yeban authored
708
ca06364 Konstantin Haase improve helpers documentation
rkh authored
709 The effect is the same as including the modules in the application class.
7abe19c Anurag Priyam README: show how to define helper functions in a separate `module`
yeban authored
710
7f7da82 Konstantin Haase document sessions
rkh authored
711 === Using Sessions
712
713 A session is used to keep state during requests. If activated, you have one
714 session hash per user session:
715
716 enable :sessions
717
718 get '/' do
719 "value = " << session[:value].inspect
720 end
721
722 get '/:value' do
723 session[:value] = params[:value]
724 end
725
726 Note that <tt>enable :sessions</tt> actually stores all data in a cookie. This
727 might not always be what you want (storing lots of data will increase your
ab7dfa6 Emanuele Vicentini README markup tweaks.
baldowl authored
728 traffic, for instance). You can use any Rack session middleware: in order to
7f7da82 Konstantin Haase document sessions
rkh authored
729 do so, do *not* call <tt>enable :sessions</tt>, but instead pull in your
9eb0dfe Konstantin Haase wording
rkh authored
730 middleware of choice as you would any other middleware:
7f7da82 Konstantin Haase document sessions
rkh authored
731
732 use Rack::Session::Pool, :expire_after => 2592000
733
734 get '/' do
735 "value = " << session[:value].inspect
736 end
737
738 get '/:value' do
739 session[:value] = params[:value]
740 end
741
87bdb85 Konstantin Haase document session_secret
rkh authored
742 To improve security, the session data in the cookie is signed with a session
743 secret. A random secret is generate for you by Sinatra. However, since this
744 secret will change with every start of your application, you might want to
745 set the secret yourself, so all your application instances share it:
746
747 set :session_secret, 'super secret'
748
0c9e3d8 Konstantin Haase accept a hash as sessions setting
rkh authored
749 If you want to configure it further, you may also store a hash with options in
750 the +sessions+ setting:
751
752 set :sessions, :domain => 'foo.com'
753
08d5682 Konstantin Haase reorganizing helpers in readme
rkh authored
754 === Halting
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
755
4e50ddb Jimmy Schementi Adds after filters
jschementi authored
756 To immediately stop a request within a filter or route use:
df800b5 Docs are started
Blake Mizerany authored
757
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
758 halt
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
759
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
760 You can also specify the status when halting:
fbbd822 Simon Rozet More 'halt' doc
sr authored
761
762 halt 410
763
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
764 Or the body:
df800b5 Docs are started
Blake Mizerany authored
765
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
766 halt 'this will be the body'
df800b5 Docs are started
Blake Mizerany authored
767
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
768 Or both:
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
769
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
770 halt 401, 'go away!'
df800b5 Docs are started
Blake Mizerany authored
771
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
772 With headers:
fbbd822 Simon Rozet More 'halt' doc
sr authored
773
774 halt 402, {'Content-Type' => 'text/plain'}, 'revenge'
775
5f5bb9d Konstantin Haase add example for halt with template
rkh authored
776 It is of course possible to combine a template with +halt+:
777
778 halt erb(:error)
779
08d5682 Konstantin Haase reorganizing helpers in readme
rkh authored
780 === Passing
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
781
5e13aa8 revert false positive spelling correction
Lee Jarvis authored
782 A route can punt processing to the next matching route using <tt>pass</tt>:
df800b5 Docs are started
Blake Mizerany authored
783
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
784 get '/guess/:who' do
785 pass unless params[:who] == 'Frank'
6c9488e Simon Rozet Stick to single quote; kill a blank line
sr authored
786 'You got me!'
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
787 end
788
789 get '/guess/*' do
6c9488e Simon Rozet Stick to single quote; kill a blank line
sr authored
790 'You missed!'
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
791 end
792
793 The route block is immediately exited and control continues with the next
794 matching route. If no matching route is found, a 404 is returned.
df800b5 Docs are started
Blake Mizerany authored
795
79c5acc Konstantin Haase document using call from within a route, fixes #141
rkh authored
796 === Triggering Another Route
797
798 Sometimes +pass+ is not what you want, instead you would like to get the result
799 of calling another route. Simply use +call+ to achieve this:
800
801 get '/foo' do
66f1256 Konstantin Haase env is accessable directly, no need to use request.env
rkh authored
802 status, headers, body = call env.merge("PATH_INFO" => '/bar')
039675f Konstantin Haase test and fix #call example
rkh authored
803 [status, headers, body.map(&:upcase)]
79c5acc Konstantin Haase document using call from within a route, fixes #141
rkh authored
804 end
805
806 get '/bar' do
807 "bar"
808 end
809
810 Note that in the example above, you would ease testing and increase performance
73e137d Konstantin Haase improve language in readme
rkh authored
811 by simply moving <tt>"bar"</tt> into a helper used by both <tt>/foo</tt>
4a659e1 burningTyger fixed some typos et al in the README
burningTyger authored
812 and <tt>/bar</tt>.
79c5acc Konstantin Haase document using call from within a route, fixes #141
rkh authored
813
814 If you want the request to be sent to the same application instance rather than
815 a duplicate, use <tt>call!</tt> instead of <tt>call</tt>.
816
817 Check out the Rack specification if you want to learn more about <tt>call</tt>.
818
b272bba Konstantin Haase document headers helper, improve documentation for status helper
rkh authored
819 === Setting Body, Status Code and Headers
9a22d7c Konstantin Haase Document body and status helper methods. Fixes #146.
rkh authored
820
821 It is possible and recommended to set the status code and response body with the
822 return value of the route block. However, in some scenarios you might want to
4a659e1 burningTyger fixed some typos et al in the README
burningTyger authored
823 set the body at an arbitrary point in the execution flow. You can do so with the
b94716c Konstantin Haase fix readme markup
rkh authored
824 +body+ helper method. If you do so, you can use that method from there on to
9a22d7c Konstantin Haase Document body and status helper methods. Fixes #146.
rkh authored
825 access the body:
826
c0e95f7 Konstantin Haase fix readme example indentation
rkh authored
827 get '/foo' do
828 body "bar"
829 end
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
830
c0e95f7 Konstantin Haase fix readme example indentation
rkh authored
831 after do
832 puts body
833 end
9a22d7c Konstantin Haase Document body and status helper methods. Fixes #146.
rkh authored
834
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
835 It is also possible to pass a block to +body+, which will be executed by the
210e342 burningTyger fix some typos in README.rdoc
burningTyger authored
836 Rack handler (this can be used to implement streaming, see "Return Values").
9a22d7c Konstantin Haase Document body and status helper methods. Fixes #146.
rkh authored
837
73e137d Konstantin Haase improve language in readme
rkh authored
838 Similar to the body, you can also set the status code and headers:
9a22d7c Konstantin Haase Document body and status helper methods. Fixes #146.
rkh authored
839
840 get '/foo' do
841 status 418
b272bba Konstantin Haase document headers helper, improve documentation for status helper
rkh authored
842 headers \
9f69232 Konstantin Haase fix teapot example
rkh authored
843 "Allow" => "BREW, POST, GET, PROPFIND, WHEN",
b272bba Konstantin Haase document headers helper, improve documentation for status helper
rkh authored
844 "Refresh" => "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt"
845 body "I'm a tea pot!"
9a22d7c Konstantin Haase Document body and status helper methods. Fixes #146.
rkh authored
846 end
847
b272bba Konstantin Haase document headers helper, improve documentation for status helper
rkh authored
848 Like +body+, +headers+ and +status+ with no arguments can be used to access
849 their current values.
850
49d4c90 Konstantin Haase add #stream helper
rkh authored
851 === Streaming Responses
852
853 Sometimes you want to start sending out data while still generating parts of
854 the response body. In extreme examples, you want to keep sending data until
855 the client closes the connection. You can use the +stream+ helper to avoid
856 creating your own wrapper:
857
858 get '/' do
859 stream do |out|
860 out << "It's gonna be legen -\n"
861 sleep 0.5
862 out << " (wait for it) \n"
863 sleep 1
864 out << "- dary!\n"
865 end
866 end
867
868 This allows you to implement streaming APIs,
869 {Server Sent Events}[http://dev.w3.org/html5/eventsource/] and can be used as
870 basis for {WebSockets}[http://en.wikipedia.org/wiki/WebSocket]. It can also be
871 used to increase throughput if some but not all content depends on a slow
872 resource.
873
874 Note that the streaming behavior, especially the number of concurrent request,
875 highly depends on the web server used to serve the application. Some servers,
876 like WEBRick, might not even support streaming at all. If the server does not
877 support streaming, the body will be sent all at once after the block passed to
470d5cd Konstantin Haase add note about shotgun
rkh authored
878 +stream+ finished executing. Streaming does not work at all with Shotgun.
49d4c90 Konstantin Haase add #stream helper
rkh authored
879
b7b2890 Konstantin Haase change the stream API while we still can
rkh authored
880 If the optional parameter is set to +keep_open+, it will not call +close+ on
881 the stream object, allowing you to close it at any later point in the
882 execution flow. This only works on evented servers, like Thin and Rainbows.
9bd71b8 burningTyger consistent colon in Readme
burningTyger authored
883 Other servers will still close the stream:
49d4c90 Konstantin Haase add #stream helper
rkh authored
884
885 set :server, :thin
886 connections = []
887
888 get '/' do
889 # keep stream open
b7b2890 Konstantin Haase change the stream API while we still can
rkh authored
890 stream(:keep_open) { |out| connections << out }
49d4c90 Konstantin Haase add #stream helper
rkh authored
891 end
892
893 post '/' do
894 # write to all open streams
895 connections.each { |out| out << params[:message] << "\n" }
896 "message sent"
897 end
898
893235e Konstantin Haase document logging
rkh authored
899 === Logging
900
901 In the request scope, the +logger+ helper exposes a +Logger+ instance:
902
903 get '/' do
904 logger.info "loading data"
905 # ...
906 end
907
908 This logger will automatically take your Rack handler's logging settings into
909 account. If logging is disabled, this method will return a dummy object, so
910 you do not have to worry in your routes and filters about it.
911
912 Note that logging is only enabled for <tt>Sinatra::Application</tt> by
913 default, so if you inherit from <tt>Sinatra::Base</tt>, you probably want to
914 enable it yourself:
915
916 class MyApp < Sinatra::Base
b95764b Konstantin Haase remove unnecessary parens from example
rkh authored
917 configure :production, :development do
893235e Konstantin Haase document logging
rkh authored
918 enable :logging
919 end
920 end
921
bf3ad8c Konstantin Haase rework logger setup
rkh authored
922 To avoid any logging middleware to be set up, set the +logging+ setting to
923 +nil+. However, keep in mind that +logger+ will in that case return +nil+. A
924 common use case is when you want to set your own logger. Sinatra will use
925 whatever it will find in <tt>env['rack.logger']</tt>.
926
e2ddc57 Konstantin Haase improve documentation for content_type, move into helpers section
rkh authored
927 === Mime Types
928
929 When using <tt>send_file</tt> or static files you may have mime types Sinatra
930 doesn't understand. Use +mime_type+ to register them by file extension:
931
d59748c Konstantin Haase improve mime_type example
rkh authored
932 configure do
933 mime_type :foo, 'text/foo'
934 end
e2ddc57 Konstantin Haase improve documentation for content_type, move into helpers section
rkh authored
935
936 You can also use it with the +content_type+ helper:
937
938 get '/' do
939 content_type :foo
940 "foo foo foo"
941 end
942
ef54086 Konstantin Haase document url helper
rkh authored
943 === Generating URLs
944
b94716c Konstantin Haase fix readme markup
rkh authored
945 For generating URLs you should use the +url+ helper method, for instance, in
ef54086 Konstantin Haase document url helper
rkh authored
946 Haml:
947
948 %a{:href => url('/foo')} foo
949
950 It takes reverse proxies and Rack routers into account, if present.
951
73e137d Konstantin Haase improve language in readme
rkh authored
952 This method is also aliased to +to+ (see below for an example).
ef54086 Konstantin Haase document url helper
rkh authored
953
2eae940 Konstantin Haase document redirect, fixes #162
rkh authored
954 === Browser Redirect
955
b94716c Konstantin Haase fix readme markup
rkh authored
956 You can trigger a browser redirect with the +redirect+ helper method:
2eae940 Konstantin Haase document redirect, fixes #162
rkh authored
957
958 get '/foo' do
da9bfde Konstantin Haase use url helper for redirects in README
rkh authored
959 redirect to('/bar')
2eae940 Konstantin Haase document redirect, fixes #162
rkh authored
960 end
961
b94716c Konstantin Haase fix readme markup
rkh authored
962 Any additional parameters are handled like arguments passed to +halt+:
2eae940 Konstantin Haase document redirect, fixes #162
rkh authored
963
da9bfde Konstantin Haase use url helper for redirects in README
rkh authored
964 redirect to('/bar'), 303
965 redirect 'http://google.com', 'wrong place, buddy'
2eae940 Konstantin Haase document redirect, fixes #162
rkh authored
966
fac44f7 Konstantin Haase document `redirect back`
rkh authored
967 You can also easily redirect back to the page the user came from with
b94716c Konstantin Haase fix readme markup
rkh authored
968 <tt>redirect back</tt>:
fac44f7 Konstantin Haase document `redirect back`
rkh authored
969
970 get '/foo' do
971 "<a href='/bar'>do something</a>"
972 end
973
974 get '/bar' do
975 do_something
976 redirect back
977 end
978
2eae940 Konstantin Haase document redirect, fixes #162
rkh authored
979 To pass arguments with a redirect, either add them to the query:
980
da9bfde Konstantin Haase use url helper for redirects in README
rkh authored
981 redirect to('/bar?sum=42')
2eae940 Konstantin Haase document redirect, fixes #162
rkh authored
982
983 Or use a session:
984
e6ab1e8 Bucky Wolfe fix readme: enable :session => enable :sessions
Igneous authored
985 enable :sessions
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
986
2eae940 Konstantin Haase document redirect, fixes #162
rkh authored
987 get '/foo' do
988 session[:secret] = 'foo'
da9bfde Konstantin Haase use url helper for redirects in README
rkh authored
989 redirect to('/bar')
2eae940 Konstantin Haase document redirect, fixes #162
rkh authored
990 end
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
991
2eae940 Konstantin Haase document redirect, fixes #162
rkh authored
992 get '/bar' do
993 session[:secret]
994 end
995
267579c Konstantin Haase document cache_control
rkh authored
996 === Cache Control
997
998 Setting your headers correctly is the foundation for proper HTTP caching.
999
1000 You can easily set the Cache-Control header with like this:
1001
1002 get '/' do
1003 cache_control :public
1004 "cache it!"
1005 end
1006
b9d49cf burningTyger Readme[.de].rdoc update
burningTyger authored
1007 Pro tip: Set up caching in a before filter:
267579c Konstantin Haase document cache_control
rkh authored
1008
1009 before do
1010 cache_control :public, :must_revalidate, :max_age => 60
1011 end
1012
b394269 Konstantin Haase document expires, last_modified and etag helpers
rkh authored
1013 If you are using the +expires+ helper to set the corresponding header,
1014 <tt>Cache-Control</tt> will be set automatically for you:
1015
1016 before do
1017 expires 500, :public, :must_revalidate
1018 end
1019
8d5fd6a Tim Preston Slight changes to wording regarding caching.
tehpeh authored
1020 To properly use caches, you should consider using +etag+ or +last_modified+.
b394269 Konstantin Haase document expires, last_modified and etag helpers
rkh authored
1021 It is recommended to call those helpers *before* doing heavy lifting, as they
1022 will immediately flush a response if the client already has the current
b9d49cf burningTyger Readme[.de].rdoc update
burningTyger authored
1023 version in its cache:
b394269 Konstantin Haase document expires, last_modified and etag helpers
rkh authored
1024
1025 get '/article/:id' do
1026 @article = Article.find params[:id]
1027 last_modified @article.updated_at
1028 etag @article.sha1
1029 erb :article
1030 end
1031
1032 It is also possible to use a
1033 {weak ETag}[http://en.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation]:
1034
1035 etag @article.sha1, :weak
1036
3690ed3 Konstantin Haase add caching example
rkh authored
1037 These helpers will not do any caching for you, but rather feed the necessary
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1038 information to your cache. If you are looking for a quick reverse-proxy caching
1039 solution, try {rack-cache}[http://rtomayko.github.com/rack-cache/]:
3690ed3 Konstantin Haase add caching example
rkh authored
1040
1041 require "rack/cache"
1042 require "sinatra"
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1043
3690ed3 Konstantin Haase add caching example
rkh authored
1044 use Rack::Cache
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1045
3690ed3 Konstantin Haase add caching example
rkh authored
1046 get '/' do
1047 cache_control :public, :max_age => 36000
1048 sleep 5
1049 "hello"
1050 end
1051
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1052 Use the <tt>:static_cache_control</tt> setting (see below) to add
e2ebe0f Konstantin Haase fix markup
rkh authored
1053 <tt>Cache-Control</tt> header info to static files.
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1054
a90d923 Konstantin Haase fix typo
rkh authored
1055 According to RFC 2616 your application should behave differently if the If-Match
0c69c7e Gabriel Andretta fix typo in readme
gnandretta authored
1056 or If-None-Match header is set to <tt>*</tt> depending on whether the resource
a90d923 Konstantin Haase fix typo
rkh authored
1057 requested is already in existence. Sinatra assumes resources for safe (like get)
1058 and idempotent (like put) requests are already in existence, whereas other
1059 resources (for instance for post requests), are treated as new resources. You
1060 can change this behavior by passing in a <tt>:new_resource</tt> option:
48e1673 Konstantin Haase properly implement If-Matches and If-None-Matches handling according to ...
rkh authored
1061
1062 get '/create' do
1063 etag '', :new_resource => true
1064 Article.create
1065 erb :new_article
1066 end
1067
1068 If you still want to use a weak ETag, pass in a <tt>:kind</tt> option:
1069
1070 etag '', :new_resource => true, :kind => :weak
1071
ec25544 Konstantin Haase document send_file, fixes #140
rkh authored
1072 === Sending Files
1073
b94716c Konstantin Haase fix readme markup
rkh authored
1074 For sending files, you can use the <tt>send_file</tt> helper method:
ec25544 Konstantin Haase document send_file, fixes #140
rkh authored
1075
1076 get '/' do
1077 send_file 'foo.png'
1078 end
1079
4a659e1 burningTyger fixed some typos et al in the README
burningTyger authored
1080 It also takes a couple of options:
ec25544 Konstantin Haase document send_file, fixes #140
rkh authored
1081
1082 send_file 'foo.png', :type => :jpg
1083
1084 The options are:
1085
bd542e9 Konstantin Haase improve readme markup for send_file documentation
rkh authored
1086 [filename]
73e137d Konstantin Haase improve language in readme
rkh authored
1087 file name, in response, defaults to the real file name.
bd542e9 Konstantin Haase improve readme markup for send_file documentation
rkh authored
1088
1089 [last_modified]
1090 value for Last-Modified header, defaults to the file's mtime.
1091
1092 [type]
1093 content type to use, guessed from the file extension if missing.
1094
1095 [disposition]
1096 used for Content-Disposition, possible values: +nil+ (default),
b40d8ca Konstantin Haase typo
rkh authored
1097 <tt>:attachment</tt> and <tt>:inline</tt>
bd542e9 Konstantin Haase improve readme markup for send_file documentation
rkh authored
1098
1099 [length]
1100 Content-Length header, defaults to file size.
ec25544 Konstantin Haase document send_file, fixes #140
rkh authored
1101
df195cd Konstantin Haase add :status option to send_file. fixes #429.
rkh authored
1102 [status]
1103 Status code to be send. Useful when sending a static file as an error page.
1104
ec25544 Konstantin Haase document send_file, fixes #140
rkh authored
1105 If supported by the Rack handler, other means than streaming from the Ruby
1106 process will be used. If you use this helper method, Sinatra will automatically
1107 handle range requests.
1108
08d5682 Konstantin Haase reorganizing helpers in readme
rkh authored
1109 === Accessing the Request Object
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
1110
b94716c Konstantin Haase fix readme markup
rkh authored
1111 The incoming request object can be accessed from request level (filter, routes,
1112 error handlers) through the <tt>request</tt> method:
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
1113
1114 # app running on http://example.com/example
1115 get '/foo' do
ec5f606 Konstantin Haase document request.accept, request.accept? and request.preferred_type
rkh authored
1116 t = %w[text/css text/html application/javascript]
1117 request.accept # ['text/html', '*/*']
1118 request.accept? 'text/xml' # true
1119 request.preferred_type(t) # 'text/html'
1120 request.body # request body sent by the client (see below)
1121 request.scheme # "http"
1122 request.script_name # "/example"
1123 request.path_info # "/foo"
1124 request.port # 80
1125 request.request_method # "GET"
1126 request.query_string # ""
1127 request.content_length # length of request.body
1128 request.media_type # media type of request.body
1129 request.host # "example.com"
1130 request.get? # true (similar methods for other verbs)
1131 request.form_data? # false
1132 request["SOME_HEADER"] # value of SOME_HEADER header
1133 request.referrer # the referrer of the client or '/'
1134 request.user_agent # user agent (used by :agent condition)
1135 request.cookies # hash of browser cookies
1136 request.xhr? # is this an ajax request?
1137 request.url # "http://example.com/example/foo"
1138 request.path # "/example/foo"
1139 request.ip # client IP address
1140 request.secure? # false (would be true over ssl)
1141 request.forwarded? # true (if running behind a reverse proxy)
1142 request.env # raw env hash handed in by Rack
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
1143 end
1144
73e137d Konstantin Haase improve language in readme
rkh authored
1145 Some options, like <tt>script_name</tt> or <tt>path_info</tt>, can also be
1fd52d1 Konstantin Haase Fix markup
rkh authored
1146 written:
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
1147
1148 before { request.path_info = "/" }
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1149
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
1150 get "/" do
1151 "all requests end up here"
1152 end
1153
1154 The <tt>request.body</tt> is an IO or StringIO object:
1155
1156 post "/api" do
1157 request.body.rewind # in case someone already read it
1158 data = JSON.parse request.body.read
1159 "Hello #{data['name']}!"
1160 end
1161
1996436 Konstantin Haase document attachment helper
rkh authored
1162 === Attachments
1163
1164 You can use the +attachment+ helper to tell the browser the response should be
b9d49cf burningTyger Readme[.de].rdoc update
burningTyger authored
1165 stored on disk rather than displayed in the browser:
1996436 Konstantin Haase document attachment helper
rkh authored
1166
1167 get '/' do
1168 attachment
1169 "store it!"
1170 end
1171
1172 You can also pass it a file name:
1173
1174 get '/' do
1175 attachment "info.txt"
1176 "store it!"
1177 end
1178
9385dd8 Konstantin Haase make time_for part of the API
rkh authored
1179 === Dealing with Date and Time
1180
1181 Sinatra offers a +time_for+ helper method, which, from the given value
1182 generates a Time object. It is also able to convert +DateTime+, +Date+ and
9bd71b8 burningTyger consistent colon in Readme
burningTyger authored
1183 similar classes:
9385dd8 Konstantin Haase make time_for part of the API
rkh authored
1184
1185 get '/' do
1186 pass if Time.now > time_for('Dec 23, 2012')
1187 "still time"
1188 end
1189
1190 This method is used internally by +expires+, +last_modified+ and akin. You can
1191 therefore easily extend the behavior of those methods by overriding +time_for+
9bd71b8 burningTyger consistent colon in Readme
burningTyger authored
1192 in your application:
9385dd8 Konstantin Haase make time_for part of the API
rkh authored
1193
1194 helpers do
1195 def time_for(value)
1196 case value
1197 when :yesterday then Time.now - 24*60*60
1198 when :tomorrow then Time.now + 24*60*60
1199 else super
1200 end
1201 end
1202 end
1203
1204 get '/' do
1205 last_modified :yesterday
1206 expires :tomorrow
1207 "hello"
1208 end
1209
4d520c6 Konstantin Haase documentation for find_template
rkh authored
1210 === Looking Up Template Files
1211
1212 The <tt>find_template</tt> helper is used to find template files for rendering:
1213
1214 find_template settings.views, 'foo', Tilt[:haml] do |file|
1215 puts "could be #{file}"
1216 end
1217
1218 This is not really useful. But it is useful that you can actually override this
1219 method to hook in your own lookup mechanism. For instance, if you want to be
1220 able to use more than one view directory:
1221
1222 set :views, ['views', 'templates']
1223
1224 helpers do
1225 def find_template(views, name, engine, &block)
1226 Array(views).each { |v| super(v, name, engine, &block) }
1227 end
1228 end
1229
73e137d Konstantin Haase improve language in readme
rkh authored
1230 Another example would be using different directories for different engines:
4d520c6 Konstantin Haase documentation for find_template
rkh authored
1231
1232 set :views, :sass => 'views/sass', :haml => 'templates', :default => 'views'
1233
1234 helpers do
1235 def find_template(views, name, engine, &block)
1236 _, folder = views.detect { |k,v| engine == Tilt[k] }
1237 folder ||= views[:default]
1238 super(folder, name, engine, &block)
1239 end
1240 end
1241
1242 You can also easily wrap this up in an extension and share with others!
1243
1244 Note that <tt>find_template</tt> does not check if the file really exists but
1245 rather calls the given block for all possible paths. This is not a performance
1246 issue, since +render+ will use +break+ as soon as a file is found. Also,
1247 template locations (and content) will be cached if you are not running in
1248 development mode. You should keep that in mind if you write a really crazy
1249 method.
1250
13fc79d Ryan Tomayko Remove support for source file reloading [#166]
rtomayko authored
1251 == Configuration
1776a80 Added Version and Docs
Blake Mizerany authored
1252
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1253 Run once, at startup, in any environment:
1776a80 Added Version and Docs
Blake Mizerany authored
1254
1255 configure do
6136da5 Konstantin Haase better documentation on how to use configure
rkh authored
1256 # setting one option
1257 set :option, 'value'
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1258
6136da5 Konstantin Haase better documentation on how to use configure
rkh authored
1259 # setting multiple options
1260 set :a => 1, :b => 2
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1261
6136da5 Konstantin Haase better documentation on how to use configure
rkh authored
1262 # same as `set :option, true`
1263 enable :option
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1264
6136da5 Konstantin Haase better documentation on how to use configure
rkh authored
1265 # same as `set :option, false`
1266 disable :option
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1267
6136da5 Konstantin Haase better documentation on how to use configure
rkh authored
1268 # you can also have dynamic settings with blocks
1269 set(:css_dir) { File.join(views, 'css') }
1776a80 Added Version and Docs
Blake Mizerany authored
1270 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
1271
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1272 Run only when the environment (RACK_ENV environment variable) is set to
13fc79d Ryan Tomayko Remove support for source file reloading [#166]
rtomayko authored
1273 <tt>:production</tt>:
1776a80 Added Version and Docs
Blake Mizerany authored
1274
1275 configure :production do
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1276 ...
1776a80 Added Version and Docs
Blake Mizerany authored
1277 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
1278
13fc79d Ryan Tomayko Remove support for source file reloading [#166]
rtomayko authored
1279 Run when the environment is set to either <tt>:production</tt> or
1280 <tt>:test</tt>:
1776a80 Added Version and Docs
Blake Mizerany authored
1281
1282 configure :production, :test do
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1283 ...
1776a80 Added Version and Docs
Blake Mizerany authored
1284 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
1285
6136da5 Konstantin Haase better documentation on how to use configure
rkh authored
1286 You can access those options via <tt>settings</tt>:
1287
1288 configure do
1289 set :foo, 'bar'
1290 end
1291
1292 get '/' do
1293 settings.foo? # => true
1294 settings.foo # => 'bar'
1295 ...
1296 end
1297
1f1e58e Konstantin Haase add rack-protection, fixes #310
rkh authored
1298 === Configuring attack protection
1299
1300 Sinatra is using
1301 {Rack::Protection}[https://github.com/rkh/rack-protection#readme] to defend
1302 you application against common, opportunistic attacks. You can easily disable
1399a7b Konstantin Haase do not encourage disabling protection
rkh authored
1303 this behavior (which will open your application to tons of common
1304 vulnerabilities):
1f1e58e Konstantin Haase add rack-protection, fixes #310
rkh authored
1305
1306 disable :protection
1307
1308 To skip a single defense layer, set +protection+ to an options hash:
1309
1310 set :protection, :except => :path_traversal
1311
1312 You can also hand in an array in order to disable a list of protections:
1313
775d460 Sergey Nartimov fix typo in readme about protection
lest authored
1314 set :protection, :except => [:path_traversal, :session_hijacking]
1f1e58e Konstantin Haase add rack-protection, fixes #310
rkh authored
1315
3297472 Konstantin Haase document available settings
rkh authored
1316 === Available Settings
1317
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1318 [absolute_redirects] If disabled, Sinatra will allow relative redirects,
1319 however, Sinatra will no longer conform with RFC 2616
1320 (HTTP 1.1), which only allows absolute redirects.
1321
1322 Enable if your app is running behind a reverse proxy that
1323 has not been set up properly. Note that the +url+ helper
1324 will still produce absolute URLs, unless you pass in
1325 +false+ as second parameter.
1326
1327 Disabled per default.
1328
1329 [add_charsets] mime types the <tt>content_type</tt> helper will
1330 automatically add the charset info to.
1331
1332 You should add to it rather than overriding this option:
1333
1334 settings.add_charsets << "application/foobar"
1335
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1336 [app_file] Path to the main application file, used to detect project
1337 root, views and public folder and inline templates.
3297472 Konstantin Haase document available settings
rkh authored
1338
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1339 [bind] IP address to bind to (default: 0.0.0.0).
1340 Only used for built-in server.
3297472 Konstantin Haase document available settings
rkh authored
1341
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1342 [default_encoding] encoding to assume if unknown
1343 (defaults to <tt>"utf-8"</tt>).
3297472 Konstantin Haase document available settings
rkh authored
1344
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1345 [dump_errors] display errors in the log.
3297472 Konstantin Haase document available settings
rkh authored
1346
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1347 [environment] current environment, defaults to <tt>ENV['RACK_ENV']</tt>,
1348 or <tt>"development"</tt> if not available.
3297472 Konstantin Haase document available settings
rkh authored
1349
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1350 [logging] use the logger.
3297472 Konstantin Haase document available settings
rkh authored
1351
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1352 [lock] Places a lock around every request, only running
1353 processing on request per Ruby process concurrently.
3297472 Konstantin Haase document available settings
rkh authored
1354
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1355 Enabled if your app is not thread-safe.
1356 Disabled per default.
3297472 Konstantin Haase document available settings
rkh authored
1357
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1358 [method_override] use <tt>_method</tt> magic to allow put/delete forms in
1359 browsers that don't support it.
3297472 Konstantin Haase document available settings
rkh authored
1360
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1361 [port] Port to listen on. Only used for built-in server.
3297472 Konstantin Haase document available settings
rkh authored
1362
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1363 [prefixed_redirects] Whether or not to insert <tt>request.script_name</tt>
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1364 into redirects if no absolute path is given. That way
1365 <tt>redirect '/foo'</tt> would behave like
1366 <tt>redirect to('/foo')</tt>. Disabled per default.
3297472 Konstantin Haase document available settings
rkh authored
1367
1f1e58e Konstantin Haase add rack-protection, fixes #310
rkh authored
1368 [protection] Whether or not to enable web attack protections. See
1369 protection section above.
1370
a8d0f9a Gabriel Andretta doc public_dir
gnandretta authored
1371 [public_dir] Alias for <tt>public_folder</tt>. See below.
1372
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1373 [public_folder] Path to the folder public files are served from. Only
1374 used if static file serving is enabled (see
1375 <tt>static</tt> setting below). Inferred from
1376 <tt>app_file</tt> setting if not set.
3297472 Konstantin Haase document available settings
rkh authored
1377
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1378 [reload_templates] whether or not to reload templates between requests.
1379 Enabled in development mode.
3297472 Konstantin Haase document available settings
rkh authored
1380
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1381 [root] Path to project root folder. Inferred from +app_file+
1382 setting if not set.
3297472 Konstantin Haase document available settings
rkh authored
1383
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1384 [raise_errors] raise exceptions (will stop application). Enabled
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1385 by default when <tt>environment</tt> is set to
1386 <tt>"test"</tt>, disabled otherwise.
3297472 Konstantin Haase document available settings
rkh authored
1387
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1388 [run] if enabled, Sinatra will handle starting the web server,
1389 do not enable if using rackup or other means.
3297472 Konstantin Haase document available settings
rkh authored
1390
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1391 [running] is the built-in server running now?
1392 do not change this setting!
3297472 Konstantin Haase document available settings
rkh authored
1393
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1394 [server] server or list of servers to use for built-in server.
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1395 defaults to ['thin', 'mongrel', 'webrick'], order
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1396 indicates priority.
3297472 Konstantin Haase document available settings
rkh authored
1397
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1398 [sessions] enable cookie based sessions support using
1399 <tt>Rack::Session::Cookie</tt>. See 'Using Sessions'
1400 section for more information.
3297472 Konstantin Haase document available settings
rkh authored
1401
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1402 [show_exceptions] show a stack trace in the browser when an exception
de361d8 Markus Prinz 'env' is actually 'environment'
cypher authored
1403 happens. Enabled by default when <tt>environment</tt>
1404 is set to <tt>"development"</tt>, disabled otherwise.
3297472 Konstantin Haase document available settings
rkh authored
1405
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1406 [static] Whether Sinatra should handle serving static files.
1407 Disable when using a Server able to do this on its own.
1408 Disabling will boost performance.
1409 Enabled per default in classic style, disabled for
1410 modular apps.
3297472 Konstantin Haase document available settings
rkh authored
1411
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1412 [static_cache_control] When Sinatra is serving static files, set this to add
e2ebe0f Konstantin Haase fix markup
rkh authored
1413 <tt>Cache-Control</tt> headers to the responses. Uses the
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1414 +cache_control+ helper. Disabled by default.
1415 Use an explicit array when setting multiple values:
1416 <tt>set :static_cache_control, [:public, :max_age => 300]</tt>
3297472 Konstantin Haase document available settings
rkh authored
1417
49d4c90 Konstantin Haase add #stream helper
rkh authored
1418 [threaded] If set to +true+, will tell Thin to use
1419 <tt>EventMachine.defer</tt> for processing the request.
1420
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1421 [views] Path to the views folder. Inferred from <tt>app_file</tt>
1422 setting if not set.
3297472 Konstantin Haase document available settings
rkh authored
1423
cbfe4d8 enviroments description added to Readme
Aleksander Dąbrowski authored
1424 == Environments
1425
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1426 There are three predefined +environments+: <tt>"development"</tt>,
1427 <tt>"production"</tt> and <tt>"test"</tt>. Environments can be set
1428 through the +RACK_ENV+ environment variable. The default value is
1429 <tt>"development"</tt>. In this mode, all templates are reloaded between
1430 requests. Special <tt>not_found</tt> and <tt>error</tt> handlers are installed
1431 for this environment so you will see a stack trace in your browser.
1432 In <tt>"production"</tt> and <tt>"test"</tt> templates are cached by default.
cbfe4d8 enviroments description added to Readme
Aleksander Dąbrowski authored
1433
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1434 To run different environments use the <tt>-e</tt> option:
cbfe4d8 enviroments description added to Readme
Aleksander Dąbrowski authored
1435
1436 ruby my_app.rb -e [ENVIRONMENT]
1437
e69485e burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1438 You can use predefined methods: +development?+, +test?+ and +production?+ to
1439 check which enviroment is currently set.
cbfe4d8 enviroments description added to Readme
Aleksander Dąbrowski authored
1440
83a1683 Konstantin Haase Use same capitalization for all headings.
rkh authored
1441 == Error Handling
1776a80 Added Version and Docs
Blake Mizerany authored
1442
73e137d Konstantin Haase improve language in readme
rkh authored
1443 Error handlers run within the same context as routes and before filters, which
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
1444 means you get all the goodies it has to offer, like <tt>haml</tt>,
1445 <tt>erb</tt>, <tt>halt</tt>, etc.
1776a80 Added Version and Docs
Blake Mizerany authored
1446
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1447 === Not Found
1776a80 Added Version and Docs
Blake Mizerany authored
1448
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1449 When a <tt>Sinatra::NotFound</tt> exception is raised, or the response's status
1450 code is 404, the <tt>not_found</tt> handler is invoked:
1776a80 Added Version and Docs
Blake Mizerany authored
1451
1452 not_found do
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
1453 'This is nowhere to be found.'
1776a80 Added Version and Docs
Blake Mizerany authored
1454 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
1455
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1456 === Error
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1457
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1458 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
1459 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
1460 <tt>sinatra.error</tt> Rack variable:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1461
1776a80 Added Version and Docs
Blake Mizerany authored
1462 error do
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1463 'Sorry there was a nasty error - ' + env['sinatra.error'].name
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1464 end
1465
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1466 Custom errors:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1467
1468 error MyCustomError do
66f1256 Konstantin Haase env is accessable directly, no need to use request.env
rkh authored
1469 'So what happened was...' + env['sinatra.error'].message
1776a80 Added Version and Docs
Blake Mizerany authored
1470 end
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1471
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1472 Then, if this happens:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1473
1474 get '/' do
1475 raise MyCustomError, 'something bad'
1476 end
1477
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1478 You get this:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1479
1480 So what happened was... something bad
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
1481
4a659e1 burningTyger fixed some typos et al in the README
burningTyger authored
1482 Alternatively, you can install an error handler for a status code:
59e797e Simon Rozet Doc for error(500) { }
sr authored
1483
1484 error 403 do
1485 'Access forbidden'
1486 end
1487
1488 get '/secret' do
1489 403
1490 end
1491
1492 Or a range:
1493
1494 error 400..510 do
1495 'Boom'
1496 end
1497
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
1498 Sinatra installs special <tt>not_found</tt> and <tt>error</tt> handlers when
1499 running under the development environment.
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1500
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
1501 == Rack Middleware
bda21f1 Ryan Tomayko add doc on using Rack middleware to README
rtomayko authored
1502
f44fb6a Ryan Tomayko grammar/formatting pass over