Skip to content
Newer
Older
100644 2033 lines (1432 sloc) 58.2 KB
df800b5 Docs are started
Blake Mizerany authored
1 = Sinatra
2
4c91e54 @watchdogtimer Web applications should not be hyphenated
watchdogtimer authored
3 Sinatra is a DSL for quickly creating web applications in Ruby with minimal
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
4 effort:
df800b5 Docs are started
Blake Mizerany authored
5
6 # myapp.rb
7 require 'sinatra'
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
8
df800b5 Docs are started
Blake Mizerany authored
9 get '/' do
10 'Hello world!'
11 end
12
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
13 Install the gem and run with:
df800b5 Docs are started
Blake Mizerany authored
14
8465d49 @rkh Avoid `require "rubygems"` and `sudo` in README.
rkh authored
15 gem install sinatra
16 ruby -rubygems myapp.rb
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
17
18 View at: http://localhost:4567
19
63a1bb3 @rkh 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 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
23 == Routes
24
73e137d @rkh improve language in readme
rkh authored
25 In Sinatra, a route is an HTTP method paired with a URL-matching pattern.
4298a77 @rtomayko 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 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
29 .. show something ..
df800b5 Docs are started
Blake Mizerany authored
30 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
31
df800b5 Docs are started
Blake Mizerany authored
32 post '/' do
33 .. create something ..
34 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
35
df800b5 Docs are started
Blake Mizerany authored
36 put '/' do
59381b5 @rkh 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 @rtomayko grammar/formatting pass over README
rtomayko authored
43
df800b5 Docs are started
Blake Mizerany authored
44 delete '/' do
45 .. annihilate something ..
46 end
59381b5 @rkh mind readme and changes
rkh authored
47
ba1fd4c @jammur Updated README.rdoc to reflect added OPTIONS request type.
jammur authored
48 options '/' do
49 .. appease something ..
50 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
51
4298a77 @rtomayko 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 @rtomayko grammar/formatting pass over README
rtomayko authored
53 matches the request is invoked.
1776a80 Added Version and Docs
Blake Mizerany authored
54
17cb177 @cypher 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 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
58 get '/hello/:name' do
ce0fe87 @scottj97 fix inaccurate comment in README
scottj97 authored
59 # matches "GET /hello/foo" and "GET /hello/bar"
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
60 # params[:name] is 'foo' or 'bar'
17cb177 @cypher 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 @rtomayko grammar/formatting pass over README
rtomayko authored
63
6569d1b @bdimcheff 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 @cypher 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 @vic Specs, documentation and fixes for splat'n routes
vic authored
73 get '/say/*/to/*' do
74 # matches /say/hello/to/world
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
75 params[:splat] # => ["hello", "world"]
9c85e99 @vic 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 @rtomayko 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 @rtomayko grammar/formatting pass over README
rtomayko authored
82
4ea9980 @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 @cypher 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 @bdimcheff 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 @aledalgrande 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 @rkh 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 @rkh Documentation for condition. Fixes GH #15.
rkh authored
110 === Conditions
111
17cb177 @cypher 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 @rtomayko 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 @rtomayko 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 @rkh fix markup for inline code in README
rkh authored
122 Other available conditions are +host_name+ and +provides+:
726feeb @rkh Documentation for condition. Fixes GH #15.
rkh authored
123
124 get '/', :host_name => /^admin\./ do
125 "Admin Area, Access denied!"
126 end
127
128 get '/', :provides => 'html' do
129 haml :index
130 end
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
131
726feeb @rkh Documentation for condition. Fixes GH #15.
rkh authored
132 get '/', :provides => ['rss', 'atom', 'xml'] do
133 builder :feed
134 end
135
136 You can easily define your own conditions:
137
138 set(:probability) { |value| condition { rand <= value } }
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
139
726feeb @rkh Documentation for condition. Fixes GH #15.
rkh authored
140 get '/win_a_car', :probability => 0.1 do
141 "You won!"
142 end
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
143
726feeb @rkh Documentation for condition. Fixes GH #15.
rkh authored
144 get '/win_a_car' do
145 "Sorry, you lost."
146 end
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
147
8b5fcf4 @yb66 added example for condition with array argument
yb66 authored
148 For a condition that takes multiple values use a splat:
149
150 set(:auth) do |*roles| # <- notice the splat here
151 condition do
152 unless logged_in? && roles.any? {|role| current_user.in_role? role }
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
153 redirect "/login/", 303
8b5fcf4 @yb66 added example for condition with array argument
yb66 authored
154 end
155 end
156 end
726feeb @rkh Documentation for condition. Fixes GH #15.
rkh authored
157
8b5fcf4 @yb66 added example for condition with array argument
yb66 authored
158 get "/my/account/", :auth => [:user, :admin] do
159 "Your Account Details"
160 end
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
161
8b5fcf4 @yb66 added example for condition with array argument
yb66 authored
162 get "/only/admin/", :auth => :admin do
163 "Only admins are allowed here!"
164 end
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
165
a64d082 @rkh capitalize heading
rkh authored
166 === Return Values
aaeb564 @rkh 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 @rkh improve language in readme
rkh authored
170 Most commonly, this is a string, as in the above examples. But other values are
aaeb564 @rkh document route return values, fixes GH #23
rkh authored
171 also accepted.
172
c6d0614 @rkh 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 @rkh document route return values, fixes GH #23
rkh authored
175
210e342 @burningTyger fix some typos in README.rdoc
burningTyger authored
176 * An Array with three elements: <tt>[status (Fixnum), headers (Hash), response
177 body (responds to #each)]</tt>
178 * An Array with two elements: <tt>[status (Fixnum), response body (responds to
179 #each)]</tt>
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
180 * An object that responds to <tt>#each</tt> and passes nothing but strings to
210e342 @burningTyger fix some typos in README.rdoc
burningTyger authored
181 the given block
aaeb564 @rkh document route return values, fixes GH #23
rkh authored
182 * A Fixnum representing the status code
183
73e137d @rkh improve language in readme
rkh authored
184 That way we can, for instance, easily implement a streaming example:
aaeb564 @rkh 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 @rkh Simplify streaming example.
rkh authored
192 get('/') { Stream.new }
aaeb564 @rkh document route return values, fixes GH #23
rkh authored
193
49d4c90 @rkh 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 @rkh 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 @rkh typo
rkh authored
208 @captures = Match.new([])
7ec4039 @rkh document custom route matchers
rkh authored
209 end
210
211 def match(str)
9c03711 @rkh typo
rkh authored
212 @captures unless @except === str
7ec4039 @rkh 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 @rtomayko 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 @cypher 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 @rkh rename public to public_folder, fixes #301
rkh authored
241 a different location by setting the <tt>:public_folder</tt> option:
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
242
d1ab58d @rkh 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 @rtomayko 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 @rtomayko 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 @rtomayko 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 @rkh 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 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
252 == Views / Templates
df800b5 Docs are started
Blake Mizerany authored
253
b9bb11d Typo corrections.
Michael Hutchinson authored
254 Each template language is exposed via its own rendering method. These
0f0fa46 @rkh DRY-up the README
rkh authored
255 methods simply return a string:
06161bf @cypher Note on passing template symbols vs. strings in README
cypher authored
256
0f0fa46 @rkh DRY-up the README
rkh authored
257 get '/' do
258 erb :index
259 end
df800b5 Docs are started
Blake Mizerany authored
260
0f0fa46 @rkh DRY-up the README
rkh authored
261 This renders <tt>views/index.erb</tt>.
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
262
0f0fa46 @rkh DRY-up the README
rkh authored
263 Instead of a template name, you can also just pass in the template content
264 directly:
801163e @bmizerany 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 @rkh DRY-up the README
rkh authored
268 erb code
df800b5 Docs are started
Blake Mizerany authored
269 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
270
0f0fa46 @rkh 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 @rkh 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 @rkh 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 @rkh DRY-up the README
rkh authored
280 Any options not understood by Sinatra will be passed on to the template
281 engine:
801163e @bmizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
282
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
283 get '/' do
0f0fa46 @rkh DRY-up the README
rkh authored
284 haml :index, :format => :html5
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
285 end
286
0f0fa46 @rkh DRY-up the README
rkh authored
287 You can also set options per template language in general:
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
288
0f0fa46 @rkh DRY-up the README
rkh authored
289 set :haml, :format => :html5
801163e @bmizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
290
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
291 get '/' do
0f0fa46 @rkh DRY-up the README
rkh authored
292 haml :index
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
293 end
294
0f0fa46 @rkh DRY-up the README
rkh authored
295 Options passed to the render method override options set via +set+.
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
296
0f0fa46 @rkh DRY-up the README
rkh authored
297 Available Options:
dd81da1 @rkh Add nokogiri helper method. Tilt supports Nokogiri for quite some tim…
rkh authored
298
0f0fa46 @rkh 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 @rkh Add nokogiri helper method. Tilt supports Nokogiri for quite some tim…
rkh authored
302
0f0fa46 @rkh 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 @rkh Add nokogiri helper method. Tilt supports Nokogiri for quite some tim…
rkh authored
306
0f0fa46 @rkh DRY-up the README
rkh authored
307 [views]
308 Views folder to load templates from. Defaults to <tt>settings.views</tt>.
dd81da1 @rkh Add nokogiri helper method. Tilt supports Nokogiri for quite some tim…
rkh authored
309
0f0fa46 @rkh 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 @rkh Add nokogiri helper method. Tilt supports Nokogiri for quite some tim…
rkh authored
313
0f0fa46 @rkh DRY-up the README
rkh authored
314 [content_type]
315 Content-Type the template produces, default depends on template language.
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
316
0f0fa46 @rkh 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 @rtomayko grammar/formatting pass over README
rtomayko authored
320
0f0fa46 @rkh 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 it looks like a typo.
gaku authored
324 template. Example: <tt>set :rdoc, :layout_engine => :erb</tt>
801163e @bmizerany closes #9779 Auto-require haml/erb/builder/sass
bmizerany authored
325
0f0fa46 @rkh 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 @nmeans Added Sass information to documentation.
nmeans authored
328
0f0fa46 @rkh DRY-up the README
rkh authored
329 set :views, settings.root + '/templates'
4144ac1 @nmeans Added Sass information to documentation.
nmeans authored
330
0f0fa46 @rkh 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 @rtomayko grammar/formatting pass over README
rtomayko authored
336
0f0fa46 @rkh 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 @rkh 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 @rkh 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 @rkh DRY-up the README
rkh authored
345 === Haml Templates
cf3c218 @pedromenezes Adding scss support through specific command
pedromenezes authored
346
f095019 @mattwildig Update README links to Haml
mattwildig authored
347 Dependency:: {haml}[http://haml.info/]
0f0fa46 @rkh DRY-up the README
rkh authored
348 File Extensions:: <tt>.haml</tt>
349 Example:: <tt>haml :index, :format => :html5</tt>
cf3c218 @pedromenezes Adding scss support through specific command
pedromenezes authored
350
0f0fa46 @rkh DRY-up the README
rkh authored
351 === Erb Templates
cf3c218 @pedromenezes Adding scss support through specific command
pedromenezes authored
352
0f0fa46 @rkh 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 @pedromenezes Adding scss support through specific command
pedromenezes authored
358
0f0fa46 @rkh DRY-up the README
rkh authored
359 === Builder Templates
cf3c218 @pedromenezes Adding scss support through specific command
pedromenezes authored
360
0f0fa46 @rkh 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 @pedromenezes Adding scss support through specific command
pedromenezes authored
364
0f0fa46 @rkh DRY-up the README
rkh authored
365 It also takes a block for inline templates (see example).
cf3c218 @pedromenezes Adding scss support through specific command
pedromenezes authored
366
0f0fa46 @rkh DRY-up the README
rkh authored
367 === Nokogiri Templates
cf3c218 @pedromenezes Adding scss support through specific command
pedromenezes authored
368
0f0fa46 @rkh DRY-up the README
rkh authored
369 Dependency:: {nokogiri}[http://nokogiri.org/]
370 File Extensions:: <tt>.nokogiri</tt>
f4efd43 @gnandretta fix copy/paste error in readme
gnandretta authored
371 Example:: <tt>nokogiri { |xml| xml.em "hi" }</tt>
621bfcb @Ptico Added Less support
Ptico authored
372
0f0fa46 @rkh DRY-up the README
rkh authored
373 It also takes a block for inline templates (see example).
621bfcb @Ptico Added Less support
Ptico authored
374
0f0fa46 @rkh DRY-up the README
rkh authored
375 === Sass Templates
621bfcb @Ptico Added Less support
Ptico authored
376
0f0fa46 @rkh 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 @Ptico Added Less support
Ptico authored
380
0f0fa46 @rkh DRY-up the README
rkh authored
381 === SCSS Templates
621bfcb @Ptico Added Less support
Ptico authored
382
0f0fa46 @rkh 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 @rkh Add liquid helper method. Tilt supports liquid for quite some time no…
rkh authored
386
0f0fa46 @rkh DRY-up the README
rkh authored
387 === Less Templates
28a3a35 @rkh Add liquid helper method. Tilt supports liquid for quite some time no…
rkh authored
388
0f0fa46 @rkh 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 @rkh Add liquid helper method. Tilt supports liquid for quite some time no…
rkh authored
392
0f0fa46 @rkh DRY-up the README
rkh authored
393 === Liquid Templates
28a3a35 @rkh Add liquid helper method. Tilt supports liquid for quite some time no…
rkh authored
394
0f0fa46 @rkh 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 @rkh Add liquid helper method. Tilt supports liquid for quite some time no…
rkh authored
398
399 Since you cannot call Ruby methods (except for +yield+) from a Liquid
0f0fa46 @rkh DRY-up the README
rkh authored
400 template, you almost always want to pass locals to it.
28a3a35 @rkh Add liquid helper method. Tilt supports liquid for quite some time no…
rkh authored
401
970169b @rkh Add markdown helper method. Tilt supports markdown for quite some tim…
rkh authored
402 === Markdown Templates
403
0f0fa46 @rkh 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 @rkh Add markdown helper method. Tilt supports markdown for quite some tim…
rkh authored
411
a743c7d @rkh 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 @rkh Add markdown helper method. Tilt supports markdown for quite some tim…
rkh authored
415
416 erb :overview, :locals => { :text => markdown(:introduction) }
417
a743c7d @rkh Add BlueCloth example to README.
rkh authored
418 Note that you may also call the +markdown+ method from within other templates:
970169b @rkh Add markdown helper method. Tilt supports markdown for quite some tim…
rkh authored
419
420 %h1 Hello From Haml!
421 %p= markdown(:greetings)
422
a0f4717 @rkh 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 @rkh DRY-up the README
rkh authored
425 template than for the layout by passing the <tt>:layout_engine</tt> option.
a743c7d @rkh Add BlueCloth example to README.
rkh authored
426
b464e02 @rkh Add textile helper method. Tilt supports textile for quite some time …
rkh authored
427 === Textile Templates
428
0f0fa46 @rkh 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 @rkh Add textile helper method. Tilt supports textile for quite some time …
rkh authored
432
a743c7d @rkh 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 @rkh Add textile helper method. Tilt supports textile for quite some time …
rkh authored
435
436 erb :overview, :locals => { :text => textile(:introduction) }
437
9fc3f1d @rkh README formatting adjustments
rkh authored
438 Note that you may also call the +textile+ method from within other templates:
b464e02 @rkh Add textile helper method. Tilt supports textile for quite some time …
rkh authored
439
440 %h1 Hello From Haml!
441 %p= textile(:greetings)
442
a0f4717 @rkh 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 @rkh DRY-up the README
rkh authored
445 template than for the layout by passing the <tt>:layout_engine</tt> option.
a0f4717 @rkh Explain how to use :layout_engine in README.
rkh authored
446
c248dba @rkh Add rdoc helper method. Tilt supports RDoc for quite some time now, b…
rkh authored
447 === RDoc Templates
448
0f0fa46 @rkh DRY-up the README
rkh authored
449 Dependency:: {rdoc}[http://rdoc.rubyforge.org/]
450 File Extensions:: <tt>.rdoc</tt>
2bd43c0 @gaku Fixed a copy-paste error.
gaku authored
451 Example:: <tt>rdoc :README, :layout_engine => :erb</tt>
c248dba @rkh Add rdoc helper method. Tilt supports RDoc for quite some time now, b…
rkh authored
452
a743c7d @rkh 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 @rkh Add rdoc helper method. Tilt supports RDoc for quite some time now, b…
rkh authored
455
456 erb :overview, :locals => { :text => rdoc(:introduction) }
457
9fc3f1d @rkh README formatting adjustments
rkh authored
458 Note that you may also call the +rdoc+ method from within other templates:
c248dba @rkh Add rdoc helper method. Tilt supports RDoc for quite some time now, b…
rkh authored
459
460 %h1 Hello From Haml!
461 %p= rdoc(:greetings)
462
a0f4717 @rkh 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 @rkh DRY-up the README
rkh authored
465 template than for the layout by passing the <tt>:layout_engine</tt> option.
a0f4717 @rkh Explain how to use :layout_engine in README.
rkh authored
466
7cb94f2 @rkh Add radius helper method. Tilt supports radius for quite some time no…
rkh authored
467 === Radius Templates
468
0f0fa46 @rkh 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 @rkh Add radius helper method. Tilt supports radius for quite some time no…
rkh authored
472
0f0fa46 @rkh 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 @rkh Add radius helper method. Tilt supports radius for quite some time no…
rkh authored
475
8ce74b3 @rkh Add markaby helper method. Tilt supports Markaby for quite some time …
rkh authored
476 === Markaby Templates
477
0f0fa46 @rkh 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 @rkh Add markaby helper method. Tilt supports Markaby for quite some time …
rkh authored
481
0f0fa46 @rkh DRY-up the README
rkh authored
482 It also takes a block for inline templates (see example).
0ff41a6 @rkh Add support for passing a block to the markaby method:
rkh authored
483
5bf54d5 @jc00ke Adding RABL support
jc00ke authored
484 === RABL Templates
485
486 Dependency:: {rabl}[https://github.com/nesquena/rabl]
487 File Extensions:: <tt>.rabl</tt>
488 Example:: <tt>rabl :index</tt>
489
ca7fbe5 @rkh Add documentation for Slim templates.
rkh authored
490 === Slim Templates
491
0f0fa46 @rkh DRY-up the README
rkh authored
492 Dependency:: {slim}[http://slim-lang.com/]
493 File Extensions:: <tt>.slim</tt>
494 Example:: <tt>slim :index</tt>
ca7fbe5 @rkh Add documentation for Slim templates.
rkh authored
495
9ce9e54 @rkh add support for creole templates
rkh authored
496 === Creole Templates
497
0f0fa46 @rkh DRY-up the README
rkh authored
498 Dependency:: {creole}[https://github.com/minad/creole]
499 File Extensions:: <tt>.creole</tt>
500 Example:: <tt>creole :wiki, :layout_engine => :erb</tt>
f58d015 @rkh Add coffee helper method. Tilt supports CoffeeScript again, but it wa…
rkh authored
501
0f0fa46 @rkh DRY-up the README
rkh authored
502 It is not possible to call methods from creole, nor to pass locals to it. You
503 therefore will usually use it in combination with another rendering engine:
de11b44 @rkh Update CoffeeScript section with requirements for ruby-coffee-script …
rkh authored
504
0f0fa46 @rkh DRY-up the README
rkh authored
505 erb :overview, :locals => { :text => creole(:introduction) }
de11b44 @rkh Update CoffeeScript section with requirements for ruby-coffee-script …
rkh authored
506
0f0fa46 @rkh DRY-up the README
rkh authored
507 Note that you may also call the +creole+ method from within other templates:
de11b44 @rkh Update CoffeeScript section with requirements for ruby-coffee-script …
rkh authored
508
0f0fa46 @rkh DRY-up the README
rkh authored
509 %h1 Hello From Haml!
510 %p= creole(:greetings)
f58d015 @rkh Add coffee helper method. Tilt supports CoffeeScript again, but it wa…
rkh authored
511
0f0fa46 @rkh DRY-up the README
rkh authored
512 Since you cannot call Ruby from Creole, you cannot use layouts written in
513 Creole. However, it is possible to use another rendering engine for the
514 template than for the layout by passing the <tt>:layout_engine</tt> option.
f58d015 @rkh Add coffee helper method. Tilt supports CoffeeScript again, but it wa…
rkh authored
515
0f0fa46 @rkh DRY-up the README
rkh authored
516 === CoffeeScript Templates
f58d015 @rkh Add coffee helper method. Tilt supports CoffeeScript again, but it wa…
rkh authored
517
0f0fa46 @rkh DRY-up the README
rkh authored
518 Dependency:: {coffee-script}[https://github.com/josh/ruby-coffee-script]
519 and a {way to execute javascript}[https://github.com/sstephenson/execjs/blob/master/README.md#readme]
520 File Extensions:: <tt>.coffee</tt>
521 Example:: <tt>coffee :index</tt>
f58d015 @rkh Add coffee helper method. Tilt supports CoffeeScript again, but it wa…
rkh authored
522
d255666 @jamiehodge add support for yajl templates, merges #450
jamiehodge authored
523 === Yajl Templates
524
525 Dependency:: {yajl-ruby}[https://github.com/brianmario/yajl-ruby]
526 File Extensions:: <tt>.yajl</tt>
527 Example:: <tt>yajl :index, :locals => { :key => 'qux' }, :callback => 'present', :variable => 'resource' </tt>
528
529 The template source is evaluated as a Ruby string, and the resulting json variable is converted #to_json.
530
531 json = { :foo => 'bar' }
532 json[:baz] = key
533
534 The <tt>:callback</tt> and <tt>:variable</tt> options can be used to decorate the rendered object.
535
536 var resource = {"foo":"bar","baz":"qux"}; present(resource);
537
4334871 @blambeau Add french and english doc about wlang in README.
blambeau authored
538 === WLang Templates
539
540 Dependency:: {wlang}[https://github.com/blambeau/wlang/]
541 File Extensions:: <tt>.wlang</tt>
542 Example:: <tt>wlang :index, :locals => { :key => 'value' }</tt>
543
544 Since calling ruby methods is not idiomatic in wlang, you almost always want to pass locals
545 to it. Layouts written in wlang and +yield+ are supported, though.
546
705c93f @rkh Rename one of the two 'Inline Templates' sections to 'Embedded Templa…
rkh authored
547 === Embedded Templates
df800b5 Docs are started
Blake Mizerany authored
548
549 get '/' do
550 haml '%div.title Hello World'
551 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
552
705c93f @rkh Rename one of the two 'Inline Templates' sections to 'Embedded Templa…
rkh authored
553 Renders the embedded template string.
df800b5 Docs are started
Blake Mizerany authored
554
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
555 === Accessing Variables in Templates
df800b5 Docs are started
Blake Mizerany authored
556
5018264 @rtomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
557 Templates are evaluated within the same context as route handlers. Instance
4a659e1 @burningTyger fixed some typos et al in the README
burningTyger authored
558 variables set in route handlers are directly accessible by templates:
df800b5 Docs are started
Blake Mizerany authored
559
560 get '/:id' do
561 @foo = Foo.find(params[:id])
95aca76 @bleything fix documentation of variable interpolation into templates
bleything authored
562 haml '%h1= @foo.name'
df800b5 Docs are started
Blake Mizerany authored
563 end
564
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
565 Or, specify an explicit Hash of local variables:
df800b5 Docs are started
Blake Mizerany authored
566
567 get '/:id' do
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
568 foo = Foo.find(params[:id])
71e5206 @baldowl Tweaked :locals example.
baldowl authored
569 haml '%h1= bar.name', :locals => { :bar => foo }
df800b5 Docs are started
Blake Mizerany authored
570 end
571
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
572 This is typically used when rendering templates as partials from within
573 other templates.
574
3ef8eed @sr Deprecate use_in_file_templates!
sr authored
575 === Inline Templates
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
576
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
577 Templates may be defined at the end of the source file:
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
578
eec7d21 @bmizerany In-file-templates are automaticly loaded for you.
bmizerany authored
579 require 'sinatra'
580
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
581 get '/' do
582 haml :index
583 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
584
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
585 __END__
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
586
f71330e @bmizerany quick doc fix
bmizerany authored
587 @@ layout
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
588 %html
589 = yield
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
590
f71330e @bmizerany quick doc fix
bmizerany authored
591 @@ index
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
592 %div.title Hello world.
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
593
6584711 @rkh Minor markup fix in README.
rkh authored
594 NOTE: Inline templates defined in the source file that requires sinatra are
ca624fd @rkh Fix the minor markup fix in README.
rkh authored
595 automatically loaded. Call <tt>enable :inline_templates</tt> explicitly if you
3ef8eed @sr Deprecate use_in_file_templates!
sr authored
596 have inline templates in other source files.
eec7d21 @bmizerany In-file-templates are automaticly loaded for you.
bmizerany authored
597
4298a77 @rtomayko Tweak README formatting; move community/contributing to website
rtomayko authored
598 === Named Templates
599
5018264 @rtomayko Tidy up README a bit; link to @sinatra on Twitter
rtomayko authored
600 Templates may also be defined using the top-level <tt>template</tt> method:
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
601
602 template :layout do
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
603 "%html\n =yield\n"
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored
604 end
605
606 template :index do
607 '%div.title Hello World!'
608 end
609
610 get '/' do
611 haml :index
612 end
613
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
614 If a template named "layout" exists, it will be used each time a template
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
615 is rendered. You can individually disable layouts by passing
616 <tt>:layout => false</tt> or disable them by default via
210e342 @burningTyger fix some typos in README.rdoc
burningTyger authored
617 <tt>set :haml, :layout => false</tt>:
578bbab @djanowski Updating README for :layout => true.
djanowski authored
618
619 get '/' do
620 haml :index, :layout => !request.xhr?
621 end
622
d7aa6a3 @rkh Add 'Associating File Extensions' section to README.
rkh authored
623 === Associating File Extensions
624
625 To associate a file extension with a template engine, use
626 <tt>Tilt.register</tt>. For instance, if you like to use the file extension
627 +tt+ for Textile templates, you can do the following:
628
629 Tilt.register :tt, Tilt[:textile]
630
4a659e1 @burningTyger fixed some typos et al in the README
burningTyger authored
631 === Adding Your Own Template Engine
9269686 @rkh Add "Adding You Own Template Engine" section to README.
rkh authored
632
633 First, register your engine with Tilt, then create a rendering method:
634
635 Tilt.register :myat, MyAwesomeTemplateEngine
636
637 helpers do
638 def myat(*args) render(:myat, *args) end
639 end
640
641 get '/' do
642 myat :index
643 end
644
645 Renders <tt>./views/index.myat</tt>. See https://github.com/rtomayko/tilt to
646 learn more about Tilt.
647
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
648 == Filters
df800b5 Docs are started
Blake Mizerany authored
649
73e137d @rkh improve language in readme
rkh authored
650 Before filters are evaluated before each request within the same
651 context as the routes will be and can modify the request and response. Instance
652 variables set in filters are accessible by routes and templates:
1776a80 Added Version and Docs
Blake Mizerany authored
653
df800b5 Docs are started
Blake Mizerany authored
654 before do
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
655 @note = 'Hi!'
656 request.path_info = '/foo/bar/baz'
657 end
658
659 get '/foo/*' do
660 @note #=> 'Hi!'
661 params[:splat] #=> 'bar/baz'
df800b5 Docs are started
Blake Mizerany authored
662 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
663
73e137d @rkh improve language in readme
rkh authored
664 After filters are evaluated after each request within the same context and can
665 also modify the request and response. Instance variables set in before filters
666 and routes are accessible by after filters:
4e50ddb @jschementi Adds after filters
jschementi authored
667
668 after do
100baab @rkh typo - I thought I fixed that before committing
rkh authored
669 puts response.status
4e50ddb @jschementi Adds after filters
jschementi authored
670 end
671
b94716c @rkh fix readme markup
rkh authored
672 Note: Unless you use the +body+ method rather than just returning a String from
380c312 @rkh Document accessing response body in after filter. Fixes #168.
rkh authored
673 the routes, the body will not yet be available in the after filter, since it is
674 generated later on.
675
73e137d @rkh improve language in readme
rkh authored
676 Filters optionally take a pattern, causing them to be evaluated only if the
677 request path matches that pattern:
da047d3 @rkh add pattern matching to before/after filters.
rkh authored
678
679 before '/protected/*' do
680 authenticate!
681 end
682
683 after '/create/:slug' do |slug|
684 session[:last_slug] = slug
685 end
686
73e137d @rkh improve language in readme
rkh authored
687 Like routes, filters also take conditions:
7a9101a @rkh Like routes, filters now also take conditions:
rkh authored
688
689 before :agent => /Songbird/ do
690 # ...
691 end
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
692
7a9101a @rkh Like routes, filters now also take conditions:
rkh authored
693 after '/blog/*', :host_name => 'example.com' do
694 # ...
695 end
696
08d5682 @rkh reorganizing helpers in readme
rkh authored
697 == Helpers
698
699 Use the top-level <tt>helpers</tt> method to define helper methods for use in
700 route handlers and templates:
701
702 helpers do
703 def bar(name)
704 "#{name}bar"
705 end
706 end
707
708 get '/:name' do
709 bar(params[:name])
710 end
711
ca06364 @rkh improve helpers documentation
rkh authored
712 Alternatively, helper methods can be separately defined in a module:
7abe19c @yeban README: show how to define helper functions in a separate `module`
yeban authored
713
714 module FooUtils
ca06364 @rkh improve helpers documentation
rkh authored
715 def foo(name) "#{name}foo" end
7abe19c @yeban README: show how to define helper functions in a separate `module`
yeban authored
716 end
717
ca06364 @rkh improve helpers documentation
rkh authored
718 module BarUtils
719 def bar(name) "#{name}bar" end
7abe19c @yeban README: show how to define helper functions in a separate `module`
yeban authored
720 end
721
ca06364 @rkh improve helpers documentation
rkh authored
722 helpers FooUtils, BarUtils
7abe19c @yeban README: show how to define helper functions in a separate `module`
yeban authored
723
ca06364 @rkh improve helpers documentation
rkh authored
724 The effect is the same as including the modules in the application class.
7abe19c @yeban README: show how to define helper functions in a separate `module`
yeban authored
725
7f7da82 @rkh document sessions
rkh authored
726 === Using Sessions
727
728 A session is used to keep state during requests. If activated, you have one
729 session hash per user session:
730
731 enable :sessions
732
733 get '/' do
734 "value = " << session[:value].inspect
735 end
736
737 get '/:value' do
738 session[:value] = params[:value]
739 end
740
741 Note that <tt>enable :sessions</tt> actually stores all data in a cookie. This
742 might not always be what you want (storing lots of data will increase your
ab7dfa6 @baldowl README markup tweaks.
baldowl authored
743 traffic, for instance). You can use any Rack session middleware: in order to
7f7da82 @rkh document sessions
rkh authored
744 do so, do *not* call <tt>enable :sessions</tt>, but instead pull in your
9eb0dfe @rkh wording
rkh authored
745 middleware of choice as you would any other middleware:
7f7da82 @rkh document sessions
rkh authored
746
747 use Rack::Session::Pool, :expire_after => 2592000
748
749 get '/' do
750 "value = " << session[:value].inspect
751 end
752
753 get '/:value' do
754 session[:value] = params[:value]
755 end
756
87bdb85 @rkh document session_secret
rkh authored
757 To improve security, the session data in the cookie is signed with a session
b9bb11d Typo corrections.
Michael Hutchinson authored
758 secret. A random secret is generated for you by Sinatra. However, since this
87bdb85 @rkh document session_secret
rkh authored
759 secret will change with every start of your application, you might want to
760 set the secret yourself, so all your application instances share it:
761
762 set :session_secret, 'super secret'
763
0c9e3d8 @rkh accept a hash as sessions setting
rkh authored
764 If you want to configure it further, you may also store a hash with options in
765 the +sessions+ setting:
766
767 set :sessions, :domain => 'foo.com'
768
08d5682 @rkh reorganizing helpers in readme
rkh authored
769 === Halting
a734cf3 @rtomayko I knew I shoulda taken that left turn at Hoboken
rtomayko authored
770
4e50ddb @jschementi Adds after filters
jschementi authored
771 To immediately stop a request within a filter or route use:
df800b5 Docs are started
Blake Mizerany authored
772
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
773 halt
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
774
c6d0614 @rkh Minor README improvements.
rkh authored
775 You can also specify the status when halting:
fbbd822 @sr More 'halt' doc
sr authored
776
777 halt 410
778
c6d0614 @rkh Minor README improvements.
rkh authored
779 Or the body:
df800b5 Docs are started
Blake Mizerany authored
780
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
781 halt 'this will be the body'
df800b5 Docs are started
Blake Mizerany authored
782
c6d0614 @rkh Minor README improvements.
rkh authored
783 Or both:
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
784
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
785 halt 401, 'go away!'
df800b5 Docs are started
Blake Mizerany authored
786
c6d0614 @rkh Minor README improvements.
rkh authored
787 With headers:
fbbd822 @sr More 'halt' doc
sr authored
788
789 halt 402, {'Content-Type' => 'text/plain'}, 'revenge'
790
5f5bb9d @rkh add example for halt with template
rkh authored
791 It is of course possible to combine a template with +halt+:
792
793 halt erb(:error)
794
08d5682 @rkh reorganizing helpers in readme
rkh authored
795 === Passing
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
796
5e13aa8 revert false positive spelling correction
Lee Jarvis authored
797 A route can punt processing to the next matching route using <tt>pass</tt>:
df800b5 Docs are started
Blake Mizerany authored
798
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
799 get '/guess/:who' do
800 pass unless params[:who] == 'Frank'
6c9488e @sr Stick to single quote; kill a blank line
sr authored
801 'You got me!'
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
802 end
803
804 get '/guess/*' do
6c9488e @sr Stick to single quote; kill a blank line
sr authored
805 'You missed!'
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
806 end
807
808 The route block is immediately exited and control continues with the next
809 matching route. If no matching route is found, a 404 is returned.
df800b5 Docs are started
Blake Mizerany authored
810
79c5acc @rkh document using call from within a route, fixes #141
rkh authored
811 === Triggering Another Route
812
813 Sometimes +pass+ is not what you want, instead you would like to get the result
814 of calling another route. Simply use +call+ to achieve this:
815
816 get '/foo' do
66f1256 @rkh env is accessable directly, no need to use request.env
rkh authored
817 status, headers, body = call env.merge("PATH_INFO" => '/bar')
039675f @rkh test and fix #call example
rkh authored
818 [status, headers, body.map(&:upcase)]
79c5acc @rkh document using call from within a route, fixes #141
rkh authored
819 end
820
821 get '/bar' do
822 "bar"
823 end
824
825 Note that in the example above, you would ease testing and increase performance
73e137d @rkh improve language in readme
rkh authored
826 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
827 and <tt>/bar</tt>.
79c5acc @rkh document using call from within a route, fixes #141
rkh authored
828
829 If you want the request to be sent to the same application instance rather than
830 a duplicate, use <tt>call!</tt> instead of <tt>call</tt>.
831
832 Check out the Rack specification if you want to learn more about <tt>call</tt>.
833
b272bba @rkh document headers helper, improve documentation for status helper
rkh authored
834 === Setting Body, Status Code and Headers
9a22d7c @rkh Document body and status helper methods. Fixes #146.
rkh authored
835
836 It is possible and recommended to set the status code and response body with the
837 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
838 set the body at an arbitrary point in the execution flow. You can do so with the
b94716c @rkh fix readme markup
rkh authored
839 +body+ helper method. If you do so, you can use that method from there on to
9a22d7c @rkh Document body and status helper methods. Fixes #146.
rkh authored
840 access the body:
841
c0e95f7 @rkh fix readme example indentation
rkh authored
842 get '/foo' do
843 body "bar"
844 end
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
845
c0e95f7 @rkh fix readme example indentation
rkh authored
846 after do
847 puts body
848 end
9a22d7c @rkh Document body and status helper methods. Fixes #146.
rkh authored
849
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
850 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
851 Rack handler (this can be used to implement streaming, see "Return Values").
9a22d7c @rkh Document body and status helper methods. Fixes #146.
rkh authored
852
73e137d @rkh improve language in readme
rkh authored
853 Similar to the body, you can also set the status code and headers:
9a22d7c @rkh Document body and status helper methods. Fixes #146.
rkh authored
854
855 get '/foo' do
856 status 418
b272bba @rkh document headers helper, improve documentation for status helper
rkh authored
857 headers \
9f69232 @rkh fix teapot example
rkh authored
858 "Allow" => "BREW, POST, GET, PROPFIND, WHEN",
b272bba @rkh document headers helper, improve documentation for status helper
rkh authored
859 "Refresh" => "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt"
860 body "I'm a tea pot!"
9a22d7c @rkh Document body and status helper methods. Fixes #146.
rkh authored
861 end
862
b272bba @rkh document headers helper, improve documentation for status helper
rkh authored
863 Like +body+, +headers+ and +status+ with no arguments can be used to access
864 their current values.
865
49d4c90 @rkh add #stream helper
rkh authored
866 === Streaming Responses
867
868 Sometimes you want to start sending out data while still generating parts of
869 the response body. In extreme examples, you want to keep sending data until
870 the client closes the connection. You can use the +stream+ helper to avoid
871 creating your own wrapper:
872
873 get '/' do
874 stream do |out|
875 out << "It's gonna be legen -\n"
876 sleep 0.5
877 out << " (wait for it) \n"
878 sleep 1
879 out << "- dary!\n"
880 end
881 end
882
883 This allows you to implement streaming APIs,
884 {Server Sent Events}[http://dev.w3.org/html5/eventsource/] and can be used as
b9bb11d Typo corrections.
Michael Hutchinson authored
885 the basis for {WebSockets}[http://en.wikipedia.org/wiki/WebSocket]. It can also be
49d4c90 @rkh add #stream helper
rkh authored
886 used to increase throughput if some but not all content depends on a slow
887 resource.
888
b9bb11d Typo corrections.
Michael Hutchinson authored
889 Note that the streaming behavior, especially the number of concurrent requests,
49d4c90 @rkh add #stream helper
rkh authored
890 highly depends on the web server used to serve the application. Some servers,
891 like WEBRick, might not even support streaming at all. If the server does not
892 support streaming, the body will be sent all at once after the block passed to
b9bb11d Typo corrections.
Michael Hutchinson authored
893 +stream+ finishes executing. Streaming does not work at all with Shotgun.
49d4c90 @rkh add #stream helper
rkh authored
894
b7b2890 @rkh change the stream API while we still can
rkh authored
895 If the optional parameter is set to +keep_open+, it will not call +close+ on
896 the stream object, allowing you to close it at any later point in the
897 execution flow. This only works on evented servers, like Thin and Rainbows.
9bd71b8 @burningTyger consistent colon in Readme
burningTyger authored
898 Other servers will still close the stream:
49d4c90 @rkh add #stream helper
rkh authored
899
900 set :server, :thin
901 connections = []
902
903 get '/' do
904 # keep stream open
b7b2890 @rkh change the stream API while we still can
rkh authored
905 stream(:keep_open) { |out| connections << out }
49d4c90 @rkh add #stream helper
rkh authored
906 end
907
908 post '/' do
909 # write to all open streams
910 connections.each { |out| out << params[:message] << "\n" }
911 "message sent"
912 end
913
893235e @rkh document logging
rkh authored
914 === Logging
915
916 In the request scope, the +logger+ helper exposes a +Logger+ instance:
917
918 get '/' do
919 logger.info "loading data"
920 # ...
921 end
922
923 This logger will automatically take your Rack handler's logging settings into
924 account. If logging is disabled, this method will return a dummy object, so
925 you do not have to worry in your routes and filters about it.
926
927 Note that logging is only enabled for <tt>Sinatra::Application</tt> by
928 default, so if you inherit from <tt>Sinatra::Base</tt>, you probably want to
929 enable it yourself:
930
931 class MyApp < Sinatra::Base
b95764b @rkh remove unnecessary parens from example
rkh authored
932 configure :production, :development do
893235e @rkh document logging
rkh authored
933 enable :logging
934 end
935 end
936
bf3ad8c @rkh rework logger setup
rkh authored
937 To avoid any logging middleware to be set up, set the +logging+ setting to
938 +nil+. However, keep in mind that +logger+ will in that case return +nil+. A
939 common use case is when you want to set your own logger. Sinatra will use
940 whatever it will find in <tt>env['rack.logger']</tt>.
941
e2ddc57 @rkh improve documentation for content_type, move into helpers section
rkh authored
942 === Mime Types
943
944 When using <tt>send_file</tt> or static files you may have mime types Sinatra
945 doesn't understand. Use +mime_type+ to register them by file extension:
946
d59748c @rkh improve mime_type example
rkh authored
947 configure do
948 mime_type :foo, 'text/foo'
949 end
e2ddc57 @rkh improve documentation for content_type, move into helpers section
rkh authored
950
951 You can also use it with the +content_type+ helper:
952
953 get '/' do
954 content_type :foo
955 "foo foo foo"
956 end
957
ef54086 @rkh document url helper
rkh authored
958 === Generating URLs
959
b94716c @rkh fix readme markup
rkh authored
960 For generating URLs you should use the +url+ helper method, for instance, in
ef54086 @rkh document url helper
rkh authored
961 Haml:
962
963 %a{:href => url('/foo')} foo
964
965 It takes reverse proxies and Rack routers into account, if present.
966
73e137d @rkh improve language in readme
rkh authored
967 This method is also aliased to +to+ (see below for an example).
ef54086 @rkh document url helper
rkh authored
968
2eae940 @rkh document redirect, fixes #162
rkh authored
969 === Browser Redirect
970
b94716c @rkh fix readme markup
rkh authored
971 You can trigger a browser redirect with the +redirect+ helper method:
2eae940 @rkh document redirect, fixes #162
rkh authored
972
973 get '/foo' do
da9bfde @rkh use url helper for redirects in README
rkh authored
974 redirect to('/bar')
2eae940 @rkh document redirect, fixes #162
rkh authored
975 end
976
b94716c @rkh fix readme markup
rkh authored
977 Any additional parameters are handled like arguments passed to +halt+:
2eae940 @rkh document redirect, fixes #162
rkh authored
978
da9bfde @rkh use url helper for redirects in README
rkh authored
979 redirect to('/bar'), 303
980 redirect 'http://google.com', 'wrong place, buddy'
2eae940 @rkh document redirect, fixes #162
rkh authored
981
fac44f7 @rkh document `redirect back`
rkh authored
982 You can also easily redirect back to the page the user came from with
b94716c @rkh fix readme markup
rkh authored
983 <tt>redirect back</tt>:
fac44f7 @rkh document `redirect back`
rkh authored
984
985 get '/foo' do
986 "<a href='/bar'>do something</a>"
987 end
988
989 get '/bar' do
990 do_something
991 redirect back
992 end
993
2eae940 @rkh document redirect, fixes #162
rkh authored
994 To pass arguments with a redirect, either add them to the query:
995
da9bfde @rkh use url helper for redirects in README
rkh authored
996 redirect to('/bar?sum=42')
2eae940 @rkh document redirect, fixes #162
rkh authored
997
998 Or use a session:
999
e6ab1e8 @Igneous fix readme: enable :session => enable :sessions
Igneous authored
1000 enable :sessions
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1001
2eae940 @rkh document redirect, fixes #162
rkh authored
1002 get '/foo' do
1003 session[:secret] = 'foo'
da9bfde @rkh use url helper for redirects in README
rkh authored
1004 redirect to('/bar')
2eae940 @rkh document redirect, fixes #162
rkh authored
1005 end
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1006
2eae940 @rkh document redirect, fixes #162
rkh authored
1007 get '/bar' do
1008 session[:secret]
1009 end
1010
267579c @rkh document cache_control
rkh authored
1011 === Cache Control
1012
1013 Setting your headers correctly is the foundation for proper HTTP caching.
1014
153c0d8 Typo corrections and minor copy editing of README.rdoc
Michael Hutchinson authored
1015 You can easily set the Cache-Control header like this:
267579c @rkh document cache_control
rkh authored
1016
1017 get '/' do
1018 cache_control :public
1019 "cache it!"
1020 end
1021
b9d49cf @burningTyger Readme[.de].rdoc update
burningTyger authored
1022 Pro tip: Set up caching in a before filter:
267579c @rkh document cache_control
rkh authored
1023
1024 before do
1025 cache_control :public, :must_revalidate, :max_age => 60
1026 end
1027
b394269 @rkh document expires, last_modified and etag helpers
rkh authored
1028 If you are using the +expires+ helper to set the corresponding header,
1029 <tt>Cache-Control</tt> will be set automatically for you:
1030
1031 before do
1032 expires 500, :public, :must_revalidate
1033 end
1034
8d5fd6a @tehpeh Slight changes to wording regarding caching.
tehpeh authored
1035 To properly use caches, you should consider using +etag+ or +last_modified+.
153c0d8 Typo corrections and minor copy editing of README.rdoc
Michael Hutchinson authored
1036 It is recommended to call those helpers *before* doing any heavy lifting, as they
b394269 @rkh document expires, last_modified and etag helpers
rkh authored
1037 will immediately flush a response if the client already has the current
b9d49cf @burningTyger Readme[.de].rdoc update
burningTyger authored
1038 version in its cache:
b394269 @rkh document expires, last_modified and etag helpers
rkh authored
1039
1040 get '/article/:id' do
1041 @article = Article.find params[:id]
1042 last_modified @article.updated_at
1043 etag @article.sha1
1044 erb :article
1045 end
1046
1047 It is also possible to use a
1048 {weak ETag}[http://en.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation]:
1049
1050 etag @article.sha1, :weak
1051
3690ed3 @rkh add caching example
rkh authored
1052 These helpers will not do any caching for you, but rather feed the necessary
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1053 information to your cache. If you are looking for a quick reverse-proxy caching
1054 solution, try {rack-cache}[http://rtomayko.github.com/rack-cache/]:
3690ed3 @rkh add caching example
rkh authored
1055
1056 require "rack/cache"
1057 require "sinatra"
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1058
3690ed3 @rkh add caching example
rkh authored
1059 use Rack::Cache
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1060
3690ed3 @rkh add caching example
rkh authored
1061 get '/' do
1062 cache_control :public, :max_age => 36000
1063 sleep 5
1064 "hello"
1065 end
1066
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1067 Use the <tt>:static_cache_control</tt> setting (see below) to add
e2ebe0f @rkh fix markup
rkh authored
1068 <tt>Cache-Control</tt> header info to static files.
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1069
a90d923 @rkh fix typo
rkh authored
1070 According to RFC 2616 your application should behave differently if the If-Match
0c69c7e @gnandretta fix typo in readme
gnandretta authored
1071 or If-None-Match header is set to <tt>*</tt> depending on whether the resource
a90d923 @rkh fix typo
rkh authored
1072 requested is already in existence. Sinatra assumes resources for safe (like get)
1073 and idempotent (like put) requests are already in existence, whereas other
1074 resources (for instance for post requests), are treated as new resources. You
1075 can change this behavior by passing in a <tt>:new_resource</tt> option:
48e1673 @rkh properly implement If-Matches and If-None-Matches handling according …
rkh authored
1076
1077 get '/create' do
1078 etag '', :new_resource => true
1079 Article.create
1080 erb :new_article
1081 end
1082
1083 If you still want to use a weak ETag, pass in a <tt>:kind</tt> option:
1084
1085 etag '', :new_resource => true, :kind => :weak
1086
ec25544 @rkh document send_file, fixes #140
rkh authored
1087 === Sending Files
1088
b94716c @rkh fix readme markup
rkh authored
1089 For sending files, you can use the <tt>send_file</tt> helper method:
ec25544 @rkh document send_file, fixes #140
rkh authored
1090
1091 get '/' do
1092 send_file 'foo.png'
1093 end
1094
153c0d8 Typo corrections and minor copy editing of README.rdoc
Michael Hutchinson authored
1095 It also takes options:
ec25544 @rkh document send_file, fixes #140
rkh authored
1096
1097 send_file 'foo.png', :type => :jpg
1098
1099 The options are:
1100
bd542e9 @rkh improve readme markup for send_file documentation
rkh authored
1101 [filename]
73e137d @rkh improve language in readme
rkh authored
1102 file name, in response, defaults to the real file name.
bd542e9 @rkh improve readme markup for send_file documentation
rkh authored
1103
1104 [last_modified]
1105 value for Last-Modified header, defaults to the file's mtime.
1106
1107 [type]
1108 content type to use, guessed from the file extension if missing.
1109
1110 [disposition]
1111 used for Content-Disposition, possible values: +nil+ (default),
b40d8ca @rkh typo
rkh authored
1112 <tt>:attachment</tt> and <tt>:inline</tt>
bd542e9 @rkh improve readme markup for send_file documentation
rkh authored
1113
1114 [length]
1115 Content-Length header, defaults to file size.
ec25544 @rkh document send_file, fixes #140
rkh authored
1116
df195cd @rkh add :status option to send_file. fixes #429.
rkh authored
1117 [status]
1118 Status code to be send. Useful when sending a static file as an error page.
1119
ec25544 @rkh document send_file, fixes #140
rkh authored
1120 If supported by the Rack handler, other means than streaming from the Ruby
1121 process will be used. If you use this helper method, Sinatra will automatically
1122 handle range requests.
1123
08d5682 @rkh reorganizing helpers in readme
rkh authored
1124 === Accessing the Request Object
df0e534 @rkh Document request object. Fixes GH #60.
rkh authored
1125
b94716c @rkh fix readme markup
rkh authored
1126 The incoming request object can be accessed from request level (filter, routes,
1127 error handlers) through the <tt>request</tt> method:
df0e534 @rkh Document request object. Fixes GH #60.
rkh authored
1128
1129 # app running on http://example.com/example
1130 get '/foo' do
ec5f606 @rkh document request.accept, request.accept? and request.preferred_type
rkh authored
1131 t = %w[text/css text/html application/javascript]
1132 request.accept # ['text/html', '*/*']
1133 request.accept? 'text/xml' # true
1134 request.preferred_type(t) # 'text/html'
1135 request.body # request body sent by the client (see below)
1136 request.scheme # "http"
1137 request.script_name # "/example"
1138 request.path_info # "/foo"
1139 request.port # 80
1140 request.request_method # "GET"
1141 request.query_string # ""
1142 request.content_length # length of request.body
1143 request.media_type # media type of request.body
1144 request.host # "example.com"
1145 request.get? # true (similar methods for other verbs)
1146 request.form_data? # false
1147 request["SOME_HEADER"] # value of SOME_HEADER header
1148 request.referrer # the referrer of the client or '/'
1149 request.user_agent # user agent (used by :agent condition)
1150 request.cookies # hash of browser cookies
1151 request.xhr? # is this an ajax request?
1152 request.url # "http://example.com/example/foo"
1153 request.path # "/example/foo"
1154 request.ip # client IP address
1155 request.secure? # false (would be true over ssl)
1156 request.forwarded? # true (if running behind a reverse proxy)
1157 request.env # raw env hash handed in by Rack
df0e534 @rkh Document request object. Fixes GH #60.
rkh authored
1158 end
1159
73e137d @rkh improve language in readme
rkh authored
1160 Some options, like <tt>script_name</tt> or <tt>path_info</tt>, can also be
1fd52d1 @rkh Fix markup
rkh authored
1161 written:
df0e534 @rkh Document request object. Fixes GH #60.
rkh authored
1162
1163 before { request.path_info = "/" }
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1164
df0e534 @rkh Document request object. Fixes GH #60.
rkh authored
1165 get "/" do
1166 "all requests end up here"
1167 end
1168
1169 The <tt>request.body</tt> is an IO or StringIO object:
1170
1171 post "/api" do
1172 request.body.rewind # in case someone already read it
1173 data = JSON.parse request.body.read
1174 "Hello #{data['name']}!"
1175 end
1176
1996436 @rkh document attachment helper
rkh authored
1177 === Attachments
1178
1179 You can use the +attachment+ helper to tell the browser the response should be
b9d49cf @burningTyger Readme[.de].rdoc update
burningTyger authored
1180 stored on disk rather than displayed in the browser:
1996436 @rkh document attachment helper
rkh authored
1181
1182 get '/' do
1183 attachment
1184 "store it!"
1185 end
1186
1187 You can also pass it a file name:
1188
1189 get '/' do
1190 attachment "info.txt"
1191 "store it!"
1192 end
1193
9385dd8 @rkh make time_for part of the API
rkh authored
1194 === Dealing with Date and Time
1195
153c0d8 Typo corrections and minor copy editing of README.rdoc
Michael Hutchinson authored
1196 Sinatra offers a +time_for+ helper method that generates a Time object
1197 from the given value. It is also able to convert +DateTime+, +Date+ and
9bd71b8 @burningTyger consistent colon in Readme
burningTyger authored
1198 similar classes:
9385dd8 @rkh make time_for part of the API
rkh authored
1199
1200 get '/' do
1201 pass if Time.now > time_for('Dec 23, 2012')
1202 "still time"
1203 end
1204
1205 This method is used internally by +expires+, +last_modified+ and akin. You can
1206 therefore easily extend the behavior of those methods by overriding +time_for+
9bd71b8 @burningTyger consistent colon in Readme
burningTyger authored
1207 in your application:
9385dd8 @rkh make time_for part of the API
rkh authored
1208
1209 helpers do
1210 def time_for(value)
1211 case value
1212 when :yesterday then Time.now - 24*60*60
1213 when :tomorrow then Time.now + 24*60*60
1214 else super
1215 end
1216 end
1217 end
1218
1219 get '/' do
1220 last_modified :yesterday
1221 expires :tomorrow
1222 "hello"
1223 end
1224
4d520c6 @rkh documentation for find_template
rkh authored
1225 === Looking Up Template Files
1226
1227 The <tt>find_template</tt> helper is used to find template files for rendering:
1228
1229 find_template settings.views, 'foo', Tilt[:haml] do |file|
1230 puts "could be #{file}"
1231 end
1232
1233 This is not really useful. But it is useful that you can actually override this
1234 method to hook in your own lookup mechanism. For instance, if you want to be
1235 able to use more than one view directory:
1236
1237 set :views, ['views', 'templates']
1238
1239 helpers do
1240 def find_template(views, name, engine, &block)
1241 Array(views).each { |v| super(v, name, engine, &block) }
1242 end
1243 end
1244
73e137d @rkh improve language in readme
rkh authored
1245 Another example would be using different directories for different engines:
4d520c6 @rkh documentation for find_template
rkh authored
1246
1247 set :views, :sass => 'views/sass', :haml => 'templates', :default => 'views'
1248
1249 helpers do
1250 def find_template(views, name, engine, &block)
1251 _, folder = views.detect { |k,v| engine == Tilt[k] }
1252 folder ||= views[:default]
1253 super(folder, name, engine, &block)
1254 end
1255 end
1256
1257 You can also easily wrap this up in an extension and share with others!
1258
1259 Note that <tt>find_template</tt> does not check if the file really exists but
1260 rather calls the given block for all possible paths. This is not a performance
1261 issue, since +render+ will use +break+ as soon as a file is found. Also,
1262 template locations (and content) will be cached if you are not running in
1263 development mode. You should keep that in mind if you write a really crazy
1264 method.
1265
13fc79d @rtomayko Remove support for source file reloading [#166]
rtomayko authored
1266 == Configuration
1776a80 Added Version and Docs
Blake Mizerany authored
1267
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1268 Run once, at startup, in any environment:
1776a80 Added Version and Docs
Blake Mizerany authored
1269
1270 configure do
6136da5 @rkh better documentation on how to use configure
rkh authored
1271 # setting one option
1272 set :option, 'value'
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1273
6136da5 @rkh better documentation on how to use configure
rkh authored
1274 # setting multiple options
1275 set :a => 1, :b => 2
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1276
6136da5 @rkh better documentation on how to use configure
rkh authored
1277 # same as `set :option, true`
1278 enable :option
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1279
6136da5 @rkh better documentation on how to use configure
rkh authored
1280 # same as `set :option, false`
1281 disable :option
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1282
6136da5 @rkh better documentation on how to use configure
rkh authored
1283 # you can also have dynamic settings with blocks
1284 set(:css_dir) { File.join(views, 'css') }
1776a80 Added Version and Docs
Blake Mizerany authored
1285 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
1286
17cb177 @cypher README and CHANGES tweaks for 0.9.0 release (#63)
cypher authored
1287 Run only when the environment (RACK_ENV environment variable) is set to
13fc79d @rtomayko Remove support for source file reloading [#166]
rtomayko authored
1288 <tt>:production</tt>:
1776a80 Added Version and Docs
Blake Mizerany authored
1289
1290 configure :production do
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
1291 ...
1776a80 Added Version and Docs
Blake Mizerany authored
1292 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
1293
13fc79d @rtomayko Remove support for source file reloading [#166]
rtomayko authored
1294 Run when the environment is set to either <tt>:production</tt> or
1295 <tt>:test</tt>:
1776a80 Added Version and Docs
Blake Mizerany authored
1296
1297 configure :production, :test do
e75f4b3 @rtomayko misc README formatting tweaks
rtomayko authored
1298 ...
1776a80 Added Version and Docs
Blake Mizerany authored
1299 end
f44fb6a @rtomayko grammar/formatting pass over README
rtomayko authored
1300
6136da5 @rkh better documentation on how to use configure
rkh authored
1301 You can access those options via <tt>settings</tt>:
1302
1303 configure do
1304 set :foo, 'bar'
1305 end
1306
1307 get '/' do
1308 settings.foo? # => true
1309 settings.foo # => 'bar'
1310 ...
1311 end
1312
1f1e58e @rkh add rack-protection, fixes #310
rkh authored
1313 === Configuring attack protection
1314
1315 Sinatra is using
1316 {Rack::Protection}[https://github.com/rkh/rack-protection#readme] to defend
1317 you application against common, opportunistic attacks. You can easily disable
153c0d8 Typo corrections and minor copy editing of README.rdoc
Michael Hutchinson authored
1318 this behavior (which will open up your application to tons of common
1399a7b @rkh do not encourage disabling protection
rkh authored
1319 vulnerabilities):
1f1e58e @rkh add rack-protection, fixes #310
rkh authored
1320
1321 disable :protection
1322
1323 To skip a single defense layer, set +protection+ to an options hash:
1324
1325 set :protection, :except => :path_traversal
1326
1327 You can also hand in an array in order to disable a list of protections:
1328
775d460 @lest fix typo in readme about protection
lest authored
1329 set :protection, :except => [:path_traversal, :session_hijacking]
1f1e58e @rkh add rack-protection, fixes #310
rkh authored
1330
3297472 @rkh document available settings
rkh authored
1331 === Available Settings
1332
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1333 [absolute_redirects] If disabled, Sinatra will allow relative redirects,
1334 however, Sinatra will no longer conform with RFC 2616
1335 (HTTP 1.1), which only allows absolute redirects.
1336
1337 Enable if your app is running behind a reverse proxy that
1338 has not been set up properly. Note that the +url+ helper
1339 will still produce absolute URLs, unless you pass in
153c0d8 Typo corrections and minor copy editing of README.rdoc
Michael Hutchinson authored
1340 +false+ as the second parameter.
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1341
1342 Disabled per default.
1343
1344 [add_charsets] mime types the <tt>content_type</tt> helper will
1345 automatically add the charset info to.
1346
1347 You should add to it rather than overriding this option:
1348
1349 settings.add_charsets << "application/foobar"
1350
e69485e @burningTyger small changes to Environment section and minor markup fixes
burningTyger authored
1351 [app_file] Path to the main application file, used to detect project
1352 root, views and public folder and inline templates.
3297472 @rkh document available settings
rkh authored
1353
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1354 [bind] IP address to bind to (default: 0.0.0.0).
1355 Only used for built-in server.
3297472 @rkh document available settings
rkh authored
1356
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1357 [default_encoding] encoding to assume if unknown
1358 (defaults to <tt>"utf-8"</tt>).
3297472 @rkh document available settings
rkh authored
1359
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1360 [dump_errors] display errors in the log.
3297472 @rkh document available settings
rkh authored
1361
48949bc update README for new :static_cache_control setting
kenichi nakamura authored
1362 [environment] current environment, defaults to <tt>ENV['RACK_ENV']</tt>,
1363 or <tt>"development"</tt> if not available.
3297472 @rkh document available settings
rkh authored
1364
48949bc update README for new :static_cache_control setting
kenichi nakamura authored