Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 2018 lines (1422 sloc) 58.873 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'
b3c76a7 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
b3c76a7 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 } }
b3c76a7 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
b3c76a7 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
b3c76a7 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 }
b3c76a7 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
b3c76a7 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
b3c76a7 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>
b3c76a7 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
002c58b Typo corrections.
Michael Hutchinson authored
254 Each template language is exposed via its own rendering method. These
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
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
83a4af3 Matt Wildig Update README links to Haml
mattwildig authored
347 Dependency:: {haml}[http://haml.info/]
0f0fa46 Konstantin Haase DRY-up the README
rkh authored
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
705c93f Konstantin Haase Rename one of the two 'Inline Templates' sections to 'Embedded Templates...
rkh authored
517 === Embedded Templates
df800b5 Docs are started
Blake Mizerany authored
518
519 get '/' do
520 haml '%div.title Hello World'
521 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
522
705c93f Konstantin Haase Rename one of the two 'Inline Templates' sections to 'Embedded Templates...
rkh authored
523 Renders the embedded template string.
df800b5 Docs are started
Blake Mizerany authored
524
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
525 === Accessing Variables in Templates
df800b5 Docs are started
Blake Mizerany authored
526
5018264 Ryan Tomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
527 Templates are evaluated within the same context as route handlers. Instance
4a659e1 burningTyger fixed some typos et al in the README
burningTyger authored
528 variables set in route handlers are directly accessible by templates:
df800b5 Docs are started
Blake Mizerany authored
529
530 get '/:id' do
531 @foo = Foo.find(params[:id])
95aca76 Ben Bleything fix documentation of variable interpolation into templates
bleything authored
532 haml '%h1= @foo.name'
df800b5 Docs are started
Blake Mizerany authored
533 end
534
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
535 Or, specify an explicit Hash of local variables:
df800b5 Docs are started
Blake Mizerany authored
536
537 get '/:id' do
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
538 foo = Foo.find(params[:id])
71e5206 Emanuele Vicentini Tweaked :locals example.
baldowl authored
539 haml '%h1= bar.name', :locals => { :bar => foo }
df800b5 Docs are started
Blake Mizerany authored
540 end
541
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
542 This is typically used when rendering templates as partials from within
543 other templates.
544
3ef8eed Simon Rozet Deprecate use_in_file_templates!
sr authored
545 === Inline Templates
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
546
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
547 Templates may be defined at the end of the source file:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
548
eec7d21 Blake Mizerany In-file-templates are automaticly loaded for you.
bmizerany authored
549 require 'sinatra'
550
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
551 get '/' do
552 haml :index
553 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
554
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
555 __END__
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
556
f71330e Blake Mizerany quick doc fix
bmizerany authored
557 @@ layout
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
558 %html
559 = yield
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
560
f71330e Blake Mizerany quick doc fix
bmizerany authored
561 @@ index
b3c76a7 burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
562 %div.title Hello world.
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
563
6584711 Konstantin Haase Minor markup fix in README.
rkh authored
564 NOTE: Inline templates defined in the source file that requires sinatra are
ca624fd Konstantin Haase Fix the minor markup fix in README.
rkh authored
565 automatically loaded. Call <tt>enable :inline_templates</tt> explicitly if you
3ef8eed Simon Rozet Deprecate use_in_file_templates!
sr authored
566 have inline templates in other source files.
eec7d21 Blake Mizerany In-file-templates are automaticly loaded for you.
bmizerany authored
567
4298a77 Ryan Tomayko Tweak README formatting; move community/contributing to website
rtomayko authored
568 === Named Templates
569
5018264 Ryan Tomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
570 Templates may also be defined using the top-level <tt>template</tt> method:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
571
572 template :layout do
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
573 "%html\n =yield\n"
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
574 end
575
576 template :index do
577 '%div.title Hello World!'
578 end
579
580 get '/' do
581 haml :index
582 end
583
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
584 If a template named "layout" exists, it will be used each time a template
b3c76a7 burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
585 is rendered. You can individually disable layouts by passing
586 <tt>:layout => false</tt> or disable them by default via
210e342 burningTyger fix some typos in README.rdoc
burningTyger authored
587 <tt>set :haml, :layout => false</tt>:
578bbab Damian Janowski Updating README for :layout => true.
djanowski authored
588
589 get '/' do
590 haml :index, :layout => !request.xhr?
591 end
592
d7aa6a3 Konstantin Haase Add 'Associating File Extensions' section to README.
rkh authored
593 === Associating File Extensions
594
595 To associate a file extension with a template engine, use
596 <tt>Tilt.register</tt>. For instance, if you like to use the file extension
597 +tt+ for Textile templates, you can do the following:
598
599 Tilt.register :tt, Tilt[:textile]
600
4a659e1 burningTyger fixed some typos et al in the README
burningTyger authored
601 === Adding Your Own Template Engine
9269686 Konstantin Haase Add "Adding You Own Template Engine" section to README.
rkh authored
602
603 First, register your engine with Tilt, then create a rendering method:
604
605 Tilt.register :myat, MyAwesomeTemplateEngine
606
607 helpers do
608 def myat(*args) render(:myat, *args) end
609 end
610
611 get '/' do
612 myat :index
613 end
614
615 Renders <tt>./views/index.myat</tt>. See https://github.com/rtomayko/tilt to
616 learn more about Tilt.
617
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
618 == Filters
df800b5 Docs are started
Blake Mizerany authored
619
73e137d Konstantin Haase improve language in readme
rkh authored
620 Before filters are evaluated before each request within the same
621 context as the routes will be and can modify the request and response. Instance
622 variables set in filters are accessible by routes and templates:
1776a80 Added Version and Docs
Blake Mizerany authored
623
df800b5 Docs are started
Blake Mizerany authored
624 before do
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
625 @note = 'Hi!'
626 request.path_info = '/foo/bar/baz'
627 end
628
629 get '/foo/*' do
630 @note #=> 'Hi!'
631 params[:splat] #=> 'bar/baz'
df800b5 Docs are started
Blake Mizerany authored
632 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
633
73e137d Konstantin Haase improve language in readme
rkh authored
634 After filters are evaluated after each request within the same context and can
635 also modify the request and response. Instance variables set in before filters
636 and routes are accessible by after filters:
4e50ddb Jimmy Schementi Adds after filters
jschementi authored
637
638 after do
100baab Konstantin Haase typo - I thought I fixed that before committing
rkh authored
639 puts response.status
4e50ddb Jimmy Schementi Adds after filters
jschementi authored
640 end
641
b94716c Konstantin Haase fix readme markup
rkh authored
642 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
643 the routes, the body will not yet be available in the after filter, since it is
644 generated later on.
645
73e137d Konstantin Haase improve language in readme
rkh authored
646 Filters optionally take a pattern, causing them to be evaluated only if the
647 request path matches that pattern:
da047d3 Konstantin Haase add pattern matching to before/after filters.
rkh authored
648
649 before '/protected/*' do
650 authenticate!
651 end
652
653 after '/create/:slug' do |slug|
654 session[:last_slug] = slug
655 end
656
73e137d Konstantin Haase improve language in readme
rkh authored
657 Like routes, filters also take conditions:
7a9101a Konstantin Haase Like routes, filters now also take conditions:
rkh authored
658
659 before :agent => /Songbird/ do
660 # ...
661 end
b3c76a7 burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
662
7a9101a Konstantin Haase Like routes, filters now also take conditions:
rkh authored
663 after '/blog/*', :host_name => 'example.com' do
664 # ...
665 end
666
08d5682 Konstantin Haase reorganizing helpers in readme
rkh authored
667 == Helpers
668
669 Use the top-level <tt>helpers</tt> method to define helper methods for use in
670 route handlers and templates:
671
672 helpers do
673 def bar(name)
674 "#{name}bar"
675 end
676 end
677
678 get '/:name' do
679 bar(params[:name])
680 end
681
09cf142 Konstantin Haase improve helpers documentation
rkh authored
682 Alternatively, helper methods can be separately defined in a module:
e112c46 Anurag Priyam README: show how to define helper functions in a separate `module`
yeban authored
683
684 module FooUtils
09cf142 Konstantin Haase improve helpers documentation
rkh authored
685 def foo(name) "#{name}foo" end
e112c46 Anurag Priyam README: show how to define helper functions in a separate `module`
yeban authored
686 end
687
09cf142 Konstantin Haase improve helpers documentation
rkh authored
688 module BarUtils
689 def bar(name) "#{name}bar" end
e112c46 Anurag Priyam README: show how to define helper functions in a separate `module`
yeban authored
690 end
691
09cf142 Konstantin Haase improve helpers documentation
rkh authored
692 helpers FooUtils, BarUtils
e112c46 Anurag Priyam README: show how to define helper functions in a separate `module`
yeban authored
693
09cf142 Konstantin Haase improve helpers documentation
rkh authored
694 The effect is the same as including the modules in the application class.
e112c46 Anurag Priyam README: show how to define helper functions in a separate `module`
yeban authored
695
7f7da82 Konstantin Haase document sessions
rkh authored
696 === Using Sessions
697
698 A session is used to keep state during requests. If activated, you have one
699 session hash per user session:
700
701 enable :sessions
702
703 get '/' do
704 "value = " << session[:value].inspect
705 end
706
707 get '/:value' do
708 session[:value] = params[:value]
709 end
710
711 Note that <tt>enable :sessions</tt> actually stores all data in a cookie. This
712 might not always be what you want (storing lots of data will increase your
ab7dfa6 Emanuele Vicentini README markup tweaks.
baldowl authored
713 traffic, for instance). You can use any Rack session middleware: in order to
7f7da82 Konstantin Haase document sessions
rkh authored
714 do so, do *not* call <tt>enable :sessions</tt>, but instead pull in your
9eb0dfe Konstantin Haase wording
rkh authored
715 middleware of choice as you would any other middleware:
7f7da82 Konstantin Haase document sessions
rkh authored
716
717 use Rack::Session::Pool, :expire_after => 2592000
718
719 get '/' do
720 "value = " << session[:value].inspect
721 end
722
723 get '/:value' do
724 session[:value] = params[:value]
725 end
726
87bdb85 Konstantin Haase document session_secret
rkh authored
727 To improve security, the session data in the cookie is signed with a session
002c58b Typo corrections.
Michael Hutchinson authored
728 secret. A random secret is generated for you by Sinatra. However, since this
87bdb85 Konstantin Haase document session_secret
rkh authored
729 secret will change with every start of your application, you might want to
730 set the secret yourself, so all your application instances share it:
731
732 set :session_secret, 'super secret'
733
0c9e3d8 Konstantin Haase accept a hash as sessions setting
rkh authored
734 If you want to configure it further, you may also store a hash with options in
735 the +sessions+ setting:
736
737 set :sessions, :domain => 'foo.com'
738
08d5682 Konstantin Haase reorganizing helpers in readme
rkh authored
739 === Halting
a734cf3 Ryan Tomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
740
4e50ddb Jimmy Schementi Adds after filters
jschementi authored
741 To immediately stop a request within a filter or route use:
df800b5 Docs are started
Blake Mizerany authored
742
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
743 halt
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
744
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
745 You can also specify the status when halting:
fbbd822 Simon Rozet More 'halt' doc
sr authored
746
747 halt 410
748
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
749 Or the body:
df800b5 Docs are started
Blake Mizerany authored
750
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
751 halt 'this will be the body'
df800b5 Docs are started
Blake Mizerany authored
752
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
753 Or both:
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
754
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
755 halt 401, 'go away!'
df800b5 Docs are started
Blake Mizerany authored
756
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
757 With headers:
fbbd822 Simon Rozet More 'halt' doc
sr authored
758
759 halt 402, {'Content-Type' => 'text/plain'}, 'revenge'
760
5f5bb9d Konstantin Haase add example for halt with template
rkh authored
761 It is of course possible to combine a template with +halt+:
762
763 halt erb(:error)
764
08d5682 Konstantin Haase reorganizing helpers in readme
rkh authored
765 === Passing
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
766
5e13aa8 revert false positive spelling correction
Lee Jarvis authored
767 A route can punt processing to the next matching route using <tt>pass</tt>:
df800b5 Docs are started
Blake Mizerany authored
768
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
769 get '/guess/:who' do
770 pass unless params[:who] == 'Frank'
6c9488e Simon Rozet Stick to single quote; kill a blank line
sr authored
771 'You got me!'
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
772 end
773
774 get '/guess/*' do
6c9488e Simon Rozet Stick to single quote; kill a blank line
sr authored
775 'You missed!'
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
776 end
777
778 The route block is immediately exited and control continues with the next
779 matching route. If no matching route is found, a 404 is returned.
df800b5 Docs are started
Blake Mizerany authored
780
79c5acc Konstantin Haase document using call from within a route, fixes #141
rkh authored
781 === Triggering Another Route
782
783 Sometimes +pass+ is not what you want, instead you would like to get the result
784 of calling another route. Simply use +call+ to achieve this:
785
786 get '/foo' do
66f1256 Konstantin Haase env is accessable directly, no need to use request.env
rkh authored
787 status, headers, body = call env.merge("PATH_INFO" => '/bar')
039675f Konstantin Haase test and fix #call example
rkh authored
788 [status, headers, body.map(&:upcase)]
79c5acc Konstantin Haase document using call from within a route, fixes #141
rkh authored
789 end
790
791 get '/bar' do
792 "bar"
793 end
794
795 Note that in the example above, you would ease testing and increase performance
73e137d Konstantin Haase improve language in readme
rkh authored
796 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
797 and <tt>/bar</tt>.
79c5acc Konstantin Haase document using call from within a route, fixes #141
rkh authored
798
799 If you want the request to be sent to the same application instance rather than
800 a duplicate, use <tt>call!</tt> instead of <tt>call</tt>.
801
802 Check out the Rack specification if you want to learn more about <tt>call</tt>.
803
b272bba Konstantin Haase document headers helper, improve documentation for status helper
rkh authored
804 === Setting Body, Status Code and Headers
9a22d7c Konstantin Haase Document body and status helper methods. Fixes #146.
rkh authored
805
806 It is possible and recommended to set the status code and response body with the
807 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
808 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
809 +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
810 access the body:
811
c0e95f7 Konstantin Haase fix readme example indentation
rkh authored
812 get '/foo' do
813 body "bar"
814 end
b3c76a7 burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
815
c0e95f7 Konstantin Haase fix readme example indentation
rkh authored
816 after do
817 puts body
818 end
9a22d7c Konstantin Haase Document body and status helper methods. Fixes #146.
rkh authored
819
b3c76a7 burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
820 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
821 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
822
73e137d Konstantin Haase improve language in readme
rkh authored
823 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
824
825 get '/foo' do
826 status 418
b272bba Konstantin Haase document headers helper, improve documentation for status helper
rkh authored
827 headers \
9f69232 Konstantin Haase fix teapot example
rkh authored
828 "Allow" => "BREW, POST, GET, PROPFIND, WHEN",
b272bba Konstantin Haase document headers helper, improve documentation for status helper
rkh authored
829 "Refresh" => "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt"
830 body "I'm a tea pot!"
9a22d7c Konstantin Haase Document body and status helper methods. Fixes #146.
rkh authored
831 end
832
b272bba Konstantin Haase document headers helper, improve documentation for status helper
rkh authored
833 Like +body+, +headers+ and +status+ with no arguments can be used to access
834 their current values.
835
49d4c90 Konstantin Haase add #stream helper
rkh authored
836 === Streaming Responses
837
838 Sometimes you want to start sending out data while still generating parts of
839 the response body. In extreme examples, you want to keep sending data until
840 the client closes the connection. You can use the +stream+ helper to avoid
841 creating your own wrapper:
842
843 get '/' do
844 stream do |out|
845 out << "It's gonna be legen -\n"
846 sleep 0.5
847 out << " (wait for it) \n"
848 sleep 1
849 out << "- dary!\n"
850 end
851 end
852
853 This allows you to implement streaming APIs,
854 {Server Sent Events}[http://dev.w3.org/html5/eventsource/] and can be used as
002c58b Typo corrections.
Michael Hutchinson authored
855 the basis for {WebSockets}[http://en.wikipedia.org/wiki/WebSocket]. It can also be
49d4c90 Konstantin Haase add #stream helper
rkh authored
856 used to increase throughput if some but not all content depends on a slow
857 resource.
858
002c58b Typo corrections.
Michael Hutchinson authored
859 Note that the streaming behavior, especially the number of concurrent requests,
49d4c90 Konstantin Haase add #stream helper
rkh authored
860 highly depends on the web server used to serve the application. Some servers,
861 like WEBRick, might not even support streaming at all. If the server does not
862 support streaming, the body will be sent all at once after the block passed to
002c58b Typo corrections.
Michael Hutchinson authored
863 +stream+ finishes executing. Streaming does not work at all with Shotgun.
49d4c90 Konstantin Haase add #stream helper
rkh authored
864
b7b2890 Konstantin Haase change the stream API while we still can
rkh authored
865 If the optional parameter is set to +keep_open+, it will not call +close+ on
866 the stream object, allowing you to close it at any later point in the
867 execution flow. This only works on evented servers, like Thin and Rainbows.
9bd71b8 burningTyger consistent colon in Readme
burningTyger authored
868 Other servers will still close the stream:
49d4c90 Konstantin Haase add #stream helper
rkh authored
869
5d41047 Anurag Priyam README: use long polling to exemplify streaming API.
yeban authored
870 # long polling
871
49d4c90 Konstantin Haase add #stream helper
rkh authored
872 set :server, :thin
873 connections = []
874
5d41047 Anurag Priyam README: use long polling to exemplify streaming API.
yeban authored
875 get '/subscribe' do
876 # register a client's interest in server events
b7b2890 Konstantin Haase change the stream API while we still can
rkh authored
877 stream(:keep_open) { |out| connections << out }
5d41047 Anurag Priyam README: use long polling to exemplify streaming API.
yeban authored
878
879 # purge dead connections
880 connections.reject!(&:closed?)
881
882 # acknowledge
883 "subscribed"
49d4c90 Konstantin Haase add #stream helper
rkh authored
884 end
885
5d41047 Anurag Priyam README: use long polling to exemplify streaming API.
yeban authored
886 post '/message' do
887 connections.each do |out|
888 # notify client that a new message has arrived
b6e77bb Konstantin Haase fix streaming example
rkh authored
889 out << params[:message] << "\n"
5d41047 Anurag Priyam README: use long polling to exemplify streaming API.
yeban authored
890
b6e77bb Konstantin Haase fix streaming example
rkh authored
891 # indicate client to connect again
5d41047 Anurag Priyam README: use long polling to exemplify streaming API.
yeban authored
892 out.close
893 end
894
895 # acknowledge
896 "message received"
49d4c90 Konstantin Haase add #stream helper
rkh authored
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
b3c76a7 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
b3c76a7 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
b3c76a7 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"
b3c76a7 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
b3c76a7 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
1102 If supported by the Rack handler, other means than streaming from the Ruby
1103 process will be used. If you use this helper method, Sinatra will automatically
1104 handle range requests.
1105
08d5682 Konstantin Haase reorganizing helpers in readme
rkh authored
1106 === Accessing the Request Object
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
1107
b94716c Konstantin Haase fix readme markup
rkh authored
1108 The incoming request object can be accessed from request level (filter, routes,
1109 error handlers) through the <tt>request</tt> method:
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
1110
1111 # app running on http://example.com/example
1112 get '/foo' do
ec5f606 Konstantin Haase document request.accept, request.accept? and request.preferred_type
rkh authored
1113 t = %w[text/css text/html application/javascript]
1114 request.accept # ['text/html', '*/*']
1115 request.accept? 'text/xml' # true
1116 request.preferred_type(t) # 'text/html'
1117 request.body # request body sent by the client (see below)
1118 request.scheme # "http"
1119 request.script_name # "/example"
1120 request.path_info # "/foo"
1121 request.port # 80
1122 request.request_method # "GET"
1123 request.query_string # ""
1124 request.content_length # length of request.body
1125 request.media_type # media type of request.body
1126 request.host # "example.com"
1127 request.get? # true (similar methods for other verbs)
1128 request.form_data? # false
7ad5523 Stanislav Chistenko Typo in README
Wolg authored
1129 request["some_param"] # value of some_param parameter. [] is a shortcut to the params hash.
ec5f606 Konstantin Haase document request.accept, request.accept? and request.preferred_type
rkh authored
1130 request.referrer # the referrer of the client or '/'
1131 request.user_agent # user agent (used by :agent condition)
1132 request.cookies # hash of browser cookies
1133 request.xhr? # is this an ajax request?
1134 request.url # "http://example.com/example/foo"
1135 request.path # "/example/foo"
1136 request.ip # client IP address
1137 request.secure? # false (would be true over ssl)
1138 request.forwarded? # true (if running behind a reverse proxy)
1139 request.env # raw env hash handed in by Rack
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
1140 end
1141
73e137d Konstantin Haase improve language in readme
rkh authored
1142 Some options, like <tt>script_name</tt> or <tt>path_info</tt>, can also be
1fd52d1 Konstantin Haase Fix markup
rkh authored
1143 written:
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
1144
1145 before { request.path_info = "/" }
b3c76a7 burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1146
df0e534 Konstantin Haase Document request object. Fixes GH #60.
rkh authored
1147 get "/" do
1148 "all requests end up here"
1149 end
1150
1151 The <tt>request.body</tt> is an IO or StringIO object:
1152
1153 post "/api" do
1154 request.body.rewind # in case someone already read it
1155 data = JSON.parse request.body.read
1156 "Hello #{data['name']}!"
1157 end
1158
1996436 Konstantin Haase document attachment helper
rkh authored
1159 === Attachments
1160
1161 You can use the +attachment+ helper to tell the browser the response should be
b9d49cf burningTyger Readme[.de].rdoc update
burningTyger authored
1162 stored on disk rather than displayed in the browser:
1996436 Konstantin Haase document attachment helper
rkh authored
1163
1164 get '/' do
1165 attachment
1166 "store it!"
1167 end
1168
1169 You can also pass it a file name:
1170
1171 get '/' do
1172 attachment "info.txt"
1173 "store it!"
1174 end
1175
9385dd8 Konstantin Haase make time_for part of the API
rkh authored
1176 === Dealing with Date and Time
1177
1178 Sinatra offers a +time_for+ helper method, which, from the given value
1179 generates a Time object. It is also able to convert +DateTime+, +Date+ and
9bd71b8 burningTyger consistent colon in Readme
burningTyger authored
1180 similar classes:
9385dd8 Konstantin Haase make time_for part of the API
rkh authored
1181
1182 get '/' do
1183 pass if Time.now > time_for('Dec 23, 2012')
1184 "still time"
1185 end
1186
1187 This method is used internally by +expires+, +last_modified+ and akin. You can
1188 therefore easily extend the behavior of those methods by overriding +time_for+
9bd71b8 burningTyger consistent colon in Readme
burningTyger authored
1189 in your application:
9385dd8 Konstantin Haase make time_for part of the API
rkh authored
1190
1191 helpers do
1192 def time_for(value)
1193 case value
1194 when :yesterday then Time.now - 24*60*60
1195 when :tomorrow then Time.now + 24*60*60
1196 else super
1197 end
1198 end
1199 end
1200
1201 get '/' do
1202 last_modified :yesterday
1203 expires :tomorrow
1204 "hello"
1205 end
1206
4d520c6 Konstantin Haase documentation for find_template
rkh authored
1207 === Looking Up Template Files
1208
1209 The <tt>find_template</tt> helper is used to find template files for rendering:
1210
1211 find_template settings.views, 'foo', Tilt[:haml] do |file|
1212 puts "could be #{file}"
1213 end
1214
1215 This is not really useful. But it is useful that you can actually override this
1216 method to hook in your own lookup mechanism. For instance, if you want to be
1217 able to use more than one view directory:
1218
1219 set :views, ['views', 'templates']
1220
1221 helpers do
1222 def find_template(views, name, engine, &block)
1223 Array(views).each { |v| super(v, name, engine, &block) }
1224 end
1225 end
1226
73e137d Konstantin Haase improve language in readme
rkh authored
1227 Another example would be using different directories for different engines:
4d520c6 Konstantin Haase documentation for find_template
rkh authored
1228
1229 set :views, :sass => 'views/sass', :haml => 'templates', :default => 'views'
1230
1231 helpers do
1232 def find_template(views, name, engine, &block)
1233 _, folder = views.detect { |k,v| engine == Tilt[k] }
1234 folder ||= views[:default]
1235 super(folder, name, engine, &block)
1236 end
1237 end
1238
1239 You can also easily wrap this up in an extension and share with others!
1240
1241 Note that <tt>find_template</tt> does not check if the file really exists but
1242 rather calls the given block for all possible paths. This is not a performance
1243 issue, since +render+ will use +break+ as soon as a file is found. Also,
1244 template locations (and content) will be cached if you are not running in
1245 development mode. You should keep that in mind if you write a really crazy
1246 method.
1247
13fc79d Ryan Tomayko Remove support for source file reloading [#166]
rtomayko authored
1248 == Configuration
1776a80 Added Version and Docs
Blake Mizerany authored
1249
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1250 Run once, at startup, in any environment:
1776a80 Added Version and Docs
Blake Mizerany authored
1251
1252 configure do
6136da5 Konstantin Haase better documentation on how to use configure
rkh authored
1253 # setting one option
1254 set :option, 'value'
b3c76a7 burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1255
6136da5 Konstantin Haase better documentation on how to use configure
rkh authored
1256 # setting multiple options
1257 set :a => 1, :b => 2
b3c76a7 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 # same as `set :option, true`
1260 enable :option
b3c76a7 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, false`
1263 disable :option
b3c76a7 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 # you can also have dynamic settings with blocks
1266 set(:css_dir) { File.join(views, 'css') }
1776a80 Added Version and Docs
Blake Mizerany authored
1267 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
1268
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1269 Run only when the environment (RACK_ENV environment variable) is set to
13fc79d Ryan Tomayko Remove support for source file reloading [#166]
rtomayko authored
1270 <tt>:production</tt>:
1776a80 Added Version and Docs
Blake Mizerany authored
1271
1272 configure :production do
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1273 ...
1776a80 Added Version and Docs
Blake Mizerany authored
1274 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
1275
13fc79d Ryan Tomayko Remove support for source file reloading [#166]
rtomayko authored
1276 Run when the environment is set to either <tt>:production</tt> or
1277 <tt>:test</tt>:
1776a80 Added Version and Docs
Blake Mizerany authored
1278
1279 configure :production, :test do
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1280 ...
1776a80 Added Version and Docs
Blake Mizerany authored
1281 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
1282
6136da5 Konstantin Haase better documentation on how to use configure
rkh authored
1283 You can access those options via <tt>settings</tt>:
1284
1285 configure do
1286 set :foo, 'bar'
1287 end
1288
1289 get '/' do
1290 settings.foo? # => true
1291 settings.foo # => 'bar'
1292 ...
1293 end
1294
1f1e58e Konstantin Haase add rack-protection, fixes #310
rkh authored
1295 === Configuring attack protection
1296
1297 Sinatra is using
1298 {Rack::Protection}[https://github.com/rkh/rack-protection#readme] to defend
1f794a5 Konstantin Haase typo
rkh authored
1299 your application against common, opportunistic attacks. You can easily disable
1300 this behavior (which will open up your application to tons of common
bfda498 Konstantin Haase do not encourage disabling protection
rkh authored
1301 vulnerabilities):
1f1e58e Konstantin Haase add rack-protection, fixes #310
rkh authored
1302
1303 disable :protection
1304
1305 To skip a single defense layer, set +protection+ to an options hash:
1306
1307 set :protection, :except => :path_traversal
1308
1309 You can also hand in an array in order to disable a list of protections:
1310
775d460 Sergey Nartimov fix typo in readme about protection
lest authored
1311 set :protection, :except => [:path_traversal, :session_hijacking]
1f1e58e Konstantin Haase add rack-protection, fixes #310
rkh authored
1312
3297472 Konstantin Haase document available settings
rkh authored
1313 === Available Settings
1314
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1315 [absolute_redirects] If disabled, Sinatra will allow relative redirects,
1316 however, Sinatra will no longer conform with RFC 2616
1317 (HTTP 1.1), which only allows absolute redirects.
1318
1319 Enable if your app is running behind a reverse proxy that
1320 has not been set up properly. Note that the +url+ helper
1321 will still produce absolute URLs, unless you pass in
1322 +false+ as second parameter.
1323
1324 Disabled per default.
1325
1326 [add_charsets] mime types the <tt>content_type</tt> helper will
1327 automatically add the charset info to.
1328
1329 You should add to it rather than overriding this option:
1330
1331 settings.add_charsets << "application/foobar"
1332
b3c76a7 burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1333 [app_file] Path to the main application file, used to detect project
1334 root, views and public folder and inline templates.
3297472 Konstantin Haase document available settings
rkh authored
1335
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1336 [bind] IP address to bind to (default: 0.0.0.0).
1337 Only used for built-in server.
3297472 Konstantin Haase document available settings
rkh authored
1338
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1339 [default_encoding] encoding to assume if unknown
1340 (defaults to <tt>"utf-8"</tt>).
3297472 Konstantin Haase document available settings
rkh authored
1341
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1342 [dump_errors] display errors in the log.
3297472 Konstantin Haase document available settings
rkh authored
1343
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1344 [environment] current environment, defaults to <tt>ENV['RACK_ENV']</tt>,
1345 or <tt>"development"</tt> if not available.
3297472 Konstantin Haase document available settings
rkh authored
1346
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1347 [logging] use the logger.
3297472 Konstantin Haase document available settings
rkh authored
1348
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1349 [lock] Places a lock around every request, only running
1350 processing on request per Ruby process concurrently.
3297472 Konstantin Haase document available settings
rkh authored
1351
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1352 Enabled if your app is not thread-safe.
1353 Disabled per default.
3297472 Konstantin Haase document available settings
rkh authored
1354
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1355 [method_override] use <tt>_method</tt> magic to allow put/delete forms in
1356 browsers that don't support it.
3297472 Konstantin Haase document available settings
rkh authored
1357
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1358 [port] Port to listen on. Only used for built-in server.
3297472 Konstantin Haase document available settings
rkh authored
1359
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1360 [prefixed_redirects] Whether or not to insert <tt>request.script_name</tt>
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1361 into redirects if no absolute path is given. That way
1362 <tt>redirect '/foo'</tt> would behave like
1363 <tt>redirect to('/foo')</tt>. Disabled per default.
3297472 Konstantin Haase document available settings
rkh authored
1364
1f1e58e Konstantin Haase add rack-protection, fixes #310
rkh authored
1365 [protection] Whether or not to enable web attack protections. See
1366 protection section above.
1367
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1368 [public_folder] Path to the folder public files are served from. Only
1369 used if static file serving is enabled (see
1370 <tt>static</tt> setting below). Inferred from
1371 <tt>app_file</tt> setting if not set.
3297472 Konstantin Haase document available settings
rkh authored
1372
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1373 [reload_templates] whether or not to reload templates between requests.
1374 Enabled in development mode.
3297472 Konstantin Haase document available settings
rkh authored
1375
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1376 [root] Path to project root folder. Inferred from +app_file+
1377 setting if not set.
3297472 Konstantin Haase document available settings
rkh authored
1378
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1379 [raise_errors] raise exceptions (will stop application). Enabled
b3c76a7 burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1380 by default when <tt>environment</tt> is set to
1381 <tt>"test"</tt>, disabled otherwise.
3297472 Konstantin Haase document available settings
rkh authored
1382
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1383 [run] if enabled, Sinatra will handle starting the web server,
1384 do not enable if using rackup or other means.
3297472 Konstantin Haase document available settings
rkh authored
1385
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1386 [running] is the built-in server running now?
1387 do not change this setting!
3297472 Konstantin Haase document available settings
rkh authored
1388
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1389 [server] server or list of servers to use for built-in server.
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1390 defaults to ['thin', 'mongrel', 'webrick'], order
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1391 indicates priority.
3297472 Konstantin Haase document available settings
rkh authored
1392
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1393 [sessions] enable cookie based sessions support using
1394 <tt>Rack::Session::Cookie</tt>. See 'Using Sessions'
1395 section for more information.
3297472 Konstantin Haase document available settings
rkh authored
1396
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1397 [show_exceptions] show a stack trace in the browser when an exception
de361d8 Markus Prinz 'env' is actually 'environment'
cypher authored
1398 happens. Enabled by default when <tt>environment</tt>
1399 is set to <tt>"development"</tt>, disabled otherwise.
bf66eb9 Mat Schaffer Include information about :after_handler exception setting
matschaffer authored
1400 Can also be set to <tt>:after_handler</tt> to trigger
1401 app-specified error handling before showing a stack
1402 trace in the browser.
3297472 Konstantin Haase document available settings
rkh authored
1403
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1404 [static] Whether Sinatra should handle serving static files.
1405 Disable when using a Server able to do this on its own.
1406 Disabling will boost performance.
1407 Enabled per default in classic style, disabled for
1408 modular apps.
3297472 Konstantin Haase document available settings
rkh authored
1409
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1410 [static_cache_control] When Sinatra is serving static files, set this to add
e2ebe0f Konstantin Haase fix markup
rkh authored
1411 <tt>Cache-Control</tt> headers to the responses. Uses the
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1412 +cache_control+ helper. Disabled by default.
1413 Use an explicit array when setting multiple values:
1414 <tt>set :static_cache_control, [:public, :max_age => 300]</tt>
3297472 Konstantin Haase document available settings
rkh authored
1415
49d4c90 Konstantin Haase add #stream helper
rkh authored
1416 [threaded] If set to +true+, will tell Thin to use
1417 <tt>EventMachine.defer</tt> for processing the request.
1418
eb0b5c3 Markus Prinz Improve settings descriptions in README
cypher authored
1419 [views] Path to the views folder. Inferred from <tt>app_file</tt>
1420 setting if not set.
3297472 Konstantin Haase document available settings
rkh authored
1421
cbfe4d8 enviroments description added to Readme
Aleksander Dąbrowski authored
1422 == Environments
1423
b3c76a7 burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1424 There are three predefined +environments+: <tt>"development"</tt>,
1425 <tt>"production"</tt> and <tt>"test"</tt>. Environments can be set
1426 through the +RACK_ENV+ environment variable. The default value is
1427 <tt>"development"</tt>. In this mode, all templates are reloaded between
1428 requests. Special <tt>not_found</tt> and <tt>error</tt> handlers are installed
1429 for this environment so you will see a stack trace in your browser.
1430 In <tt>"production"</tt> and <tt>"test"</tt> templates are cached by default.
cbfe4d8 enviroments description added to Readme
Aleksander Dąbrowski authored
1431
b3c76a7 burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1432 To run different environments use the <tt>-e</tt> option:
cbfe4d8 enviroments description added to Readme
Aleksander Dąbrowski authored
1433
1434 ruby my_app.rb -e [ENVIRONMENT]
1435
b3c76a7 burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1436 You can use predefined methods: +development?+, +test?+ and +production?+ to
1437 check which enviroment is currently set.
cbfe4d8 enviroments description added to Readme
Aleksander Dąbrowski authored
1438
83a1683 Konstantin Haase Use same capitalization for all headings.
rkh authored
1439 == Error Handling
1776a80 Added Version and Docs
Blake Mizerany authored
1440
73e137d Konstantin Haase improve language in readme
rkh authored
1441 Error handlers run within the same context as routes and before filters, which
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
1442 means you get all the goodies it has to offer, like <tt>haml</tt>,
1443 <tt>erb</tt>, <tt>halt</tt>, etc.
1776a80 Added Version and Docs
Blake Mizerany authored
1444
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1445 === Not Found
1776a80 Added Version and Docs
Blake Mizerany authored
1446
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1447 When a <tt>Sinatra::NotFound</tt> exception is raised, or the response's status
1448 code is 404, the <tt>not_found</tt> handler is invoked:
1776a80 Added Version and Docs
Blake Mizerany authored
1449
1450 not_found do
c6d0614 Konstantin Haase Minor README improvements.
rkh authored
1451 'This is nowhere to be found.'
1776a80 Added Version and Docs
Blake Mizerany authored
1452 end
f44fb6a Ryan Tomayko grammar/formatting pass over README
rtomayko authored
1453
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1454 === Error
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1455
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1456 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
1457 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
1458 <tt>sinatra.error</tt> Rack variable:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1459
1776a80 Added Version and Docs
Blake Mizerany authored
1460 error do
17cb177 Markus Prinz README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1461 'Sorry there was a nasty error - ' + env['sinatra.error'].name
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1462 end
1463
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1464 Custom errors:
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1465
1466 error MyCustomError do
66f1256 Konstantin Haase env is accessable directly, no need to use request.env
rkh authored
1467 'So what happened was...' + env['sinatra.error'].message
1776a80 Added Version and Docs
Blake Mizerany authored
1468 end
83cba9c Blake Mizerany updated README with helpful tidbits
bmizerany authored
1469
e75f4b3 Ryan Tomayko misc README formatting tweaks
rtomayko authored
1470 Then, if this happens:
83cba9c Blake Mizerany updated README with helpful tidbits