Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 401 lines (282 sloc) 11.931 kb
e02e26fe » rtomayko
2009-01-29 Add FAQ
1 ---
2 title: "Sinatra: Frequently Asked Questions"
3 layout: default
4 ---
5
6 Frequently Asked Questions
7 ==========================
8
f66ee558 » sr
2009-02-16 Table of content on FAQ
9 * this will become the toc
10 {:toc}
11
6e5822df » rtomayko
2009-06-15 Add a section on reloading to the FAQ
12 What happened to reloading in Sinatra 0.9.2? {#reloading}
13 --------------------------------------------
14
15 Source file reloading was removed in the 0.9.2 due to excess complexity.
c79f41ba » rkh
2010-04-14 reloading
16
8416d4fb » rkh
2011-10-30 update reloading info in faq
17 For reloading Sinatra we recommend either using the
18 [reloader](/contrib/reloader) or
19 [shotgun](http://rtomayko.github.com/shotgun/).
c79f41ba » rkh
2010-04-14 reloading
20
8416d4fb » rkh
2011-10-30 update reloading info in faq
21 The reloader will reload single files that changed, whereas shotgun will
22 restart the HTTP server on every request. See ["Reloading Ruby
23 Code"](http://rkh.im/code-reloading) to learn more about the differences.
6e5822df » rtomayko
2009-06-15 Add a section on reloading to the FAQ
24
f66ee558 » sr
2009-02-16 Table of content on FAQ
25 What are my deployment options? {#deploy}
26 -------------------------------
2c2dd427 » bmizerany
2009-02-10 Deployment is the #1 question I get most often
27
28 See the [book](book.html#deployment).
29
f66ee558 » sr
2009-02-16 Table of content on FAQ
30 How do I use sessions? {#sessions}
31 ----------------------
e02e26fe » rtomayko
2009-01-29 Add FAQ
32
33 Sessions are disabled by default. You need to enable them and then use the
34 `session` hash from routes and views:
35
36 enable :sessions
37
38 get '/foo' do
39 session[:message] = 'Hello World!'
40 redirect '/bar'
41 end
42
43 get '/bar' do
44 session[:message] # => 'Hello World!'
45 end
46
4ec3b406 » karmi
2009-04-13 Added information about how to set additional parameters for sessions…
47 If you need to set additional parameters for sessions, like expiration date, use [`Rack::Session::Cookie`](http://rack.rubyforge.org/doc/classes/Rack/Session/Cookie.html) directly instead of `enable :sessions` (example from _Rack_ documentation):
48
49 use Rack::Session::Cookie, :key => 'rack.session',
50 :domain => 'foo.com',
51 :path => '/',
52 :expire_after => 2592000, # In seconds
53 :secret => 'change_me'
54
373b8b10 » sr
2009-02-26 Add sinatra-flash both to lib list and FAQ
55 How do I use session-based flash? {#flash}
56 --------------------------------
57
9c4eb62a » nakajima
2009-03-17 fixed Rack::Flash link
58 Use [Rack::Flash](http://github.com/nakajima/rack-flash).
373b8b10 » sr
2009-02-26 Add sinatra-flash both to lib list and FAQ
59
f66ee558 » sr
2009-02-16 Table of content on FAQ
60 Can I run Sinatra under Ruby 1.9? {#ruby19}
61 ---------------------------------
25dc5023 » rtomayko
2009-01-30 FAQ: Can I run Sinatra under Ruby 1.9?
62
83beeebe » rtomayko
2009-06-15 Update Ruby 1.9 FAQ
63 Yes. As of Sinatra 0.9.2, Sinatra is fully Ruby 1.9 and Rack 1.0 compatible.
bee79e74 » rkh
2011-01-04 Add note about 1.1 in 1.9 FAQ entry
64 Since 1.1 you do not have to deal with encodings on your own, unless you want to.
25dc5023 » rtomayko
2009-01-30 FAQ: Can I run Sinatra under Ruby 1.9?
65
f66ee558 » sr
2009-02-16 Table of content on FAQ
66 How do I get the "route" for the current page? {#path_info}
67 ----------------------------------------------
e02e26fe » rtomayko
2009-01-29 Add FAQ
68
69 The `request` object probably has what you're looking for:
70
71 get '/hello-world' do
72 request.path_info # => '/hello-world'
73 request.fullpath # => '/hello-world?foo=bar'
74 request.url # => 'http://example.com/hello-world?foo=bar'
75 end
76
77 See [Rack::Request](http://rack.rubyforge.org/doc/classes/Rack/Request.html)
78 for a detailed list of methods supported by the `request` object.
79
f66ee558 » sr
2009-02-16 Table of content on FAQ
80 How do I access helpers from within my views? {#helpview}
81 ---------------------------------------------
e02e26fe » rtomayko
2009-01-29 Add FAQ
82
83 Call them! Views automatically have access to all helper methods. In fact,
84 Sinatra evaluates routes, views, and helpers within the same exact object
85 context so they all have access to the same methods and instance variables.
86
87 In `hello.rb`:
88
89 helpers do
90 def em(text)
91 "<em>#{text}</em>"
92 end
93 end
94
95 get '/hello' do
96 @subject = 'World'
97 haml :hello
98 end
99
100 In `views/hello.haml`:
101
102 %p= "Hello " + em(@subject)
103
f66ee558 » sr
2009-02-16 Table of content on FAQ
104 How do I render partials? {#partials}
105 -------------------------
e02e26fe » rtomayko
2009-01-29 Add FAQ
106
9e03a299 » rkh
2010-12-11 improve partials section in readme
107 Sinatra's template system is simple enough that it can be used for page and
108 fragment level rendering tasks. The `erb` and `haml` methods simply return a
109 string.
ba63ac70 » rkh
2010-10-29 Update parials section in FAQ.
110
9e03a299 » rkh
2010-12-11 improve partials section in readme
111 Since Sinatra 1.1, you can use the same calls for partials you use in the routes:
ba63ac70 » rkh
2010-10-29 Update parials section in FAQ.
112
9e03a299 » rkh
2010-12-11 improve partials section in readme
113 <%= erb :mypartial %>
ba63ac70 » rkh
2010-10-29 Update parials section in FAQ.
114
9e03a299 » rkh
2010-12-11 improve partials section in readme
115 In versions prior to 1.1, you need to make sure you disable layout rendering as
e02e26fe » rtomayko
2009-01-29 Add FAQ
116 follows:
117
9e03a299 » rkh
2010-12-11 improve partials section in readme
118 <%= erb :mypartial, :layout => false %>
e02e26fe » rtomayko
2009-01-29 Add FAQ
119
7e63e50e » lenary
2012-04-10 Recommend the Sinatra-Partials gem from myself (@lenary) and @yb66.
120 See [Sam Elliott](http://www.lenary.co.uk/) and [Iain Barnett](http://iainbarnett.me.uk/)'s
121 [Sinatra-Partial extension](https://github.com/yb66/Sinatra-Partial)
122 for a more robust partials implementation. It also supports rendering
123 collections and partials in subdirectories.
6bd4ca13 » lenary
2009-08-25 Updated the partials entry in the FAQ
124
7e63e50e » lenary
2012-04-10 Recommend the Sinatra-Partials gem from myself (@lenary) and @yb66.
125 The code used to live in a [gist](https://gist.github.com/119874),
126 but we have put it in a gem so we can maintain it properly and
127 provide an easier way for developers to include its behaviour.
128 It was adapted from [Chris Schneider](http://www.gittr.com/)'s
129 original [partials.rb](http://github.com/cschneid/irclogger/blob/master/lib/partials.rb)
130 implementation.
131
132 Use it as follows to render the `mypartial.haml`(1) or the `admin/mypartial.haml`(2)
133 partials, or with a collection (3) & (4):
6bd4ca13 » lenary
2009-08-25 Updated the partials entry in the FAQ
134
135 <%= partial(:mypartial) %> <!--(1)-->
136 <%= partial(:'admin/mypartial') %> <!--(2)-->
137 <%= partial(:object, :collection => @objects) %> <!--(3)-->
138 <%= partial(:'admin/object', :collection => @objects) %> <!--(4)-->
139
7e63e50e » lenary
2012-04-10 Recommend the Sinatra-Partials gem from myself (@lenary) and @yb66.
140 In (1) & (2), the partial will be rendered plain from their files, with no
141 local variables (specify them with a hash passed into `:locals`).
142 In (3) & (4), the partials will be rendered, populating the local
143 variable `object` with each of the objects from the collection.
144
145 It is also possible to enable using underscores, a la Rails, and
146 to choose a different rendering engine from haml.
6bd4ca13 » lenary
2009-08-25 Updated the partials entry in the FAQ
147
e02e26fe » rtomayko
2009-01-29 Add FAQ
148
f66ee558 » sr
2009-02-16 Table of content on FAQ
149 Can I have multiple URLs trigger the same route/handler? {#multiroute}
150 --------------------------------------------------------
e02e26fe » rtomayko
2009-01-29 Add FAQ
151
152 Sure:
153
154 ["/foo", "/bar", "/baz"].each do |path|
155 get path do
156 "You've reached me at #{request.path_info}"
157 end
158 end
159
160 Seriously.
161
f66ee558 » sr
2009-02-16 Table of content on FAQ
162 How do I make the trailing slash optional? {#slash}
163 ------------------------------------------
e02e26fe » rtomayko
2009-01-29 Add FAQ
164
165 Put a question mark after it:
166
167 get '/foo/bar/?' do
168 "Hello World"
169 end
170
171 The route matches `"/foo/bar"` and `"/foo/bar/"`.
172
f66ee558 » sr
2009-02-16 Table of content on FAQ
173 How do I render templates nested in subdirectories? {#subdir}
174 ---------------------------------------------------
eb3656d2 » rtomayko
2009-01-30 FAQ: How do I render templates nested in subdirectories?
175
5b5a4551 » halorgium
2009-03-11 Correctly spell hierarchy
176 Sinatra apps do not typically have a very complex file hierarchy under
eb3656d2 » rtomayko
2009-01-30 FAQ: How do I render templates nested in subdirectories?
177 `views`. First, consider whether you really need subdirectories at all.
178 If so, you can use the `views/foo/bar.haml` file as a template with:
179
180 get '/' do
181 haml :'foo/bar'
182 end
183
184 This is basically the same as sending `#to_sym` to the filename and can also
185 be written as:
186
187 get '/' do
188 haml 'foo/bar'.to_sym
189 end
190
f66ee558 » sr
2009-02-16 Table of content on FAQ
191 I'm running Thin and an error occurs but there's no output {#thindebug}
192 ----------------------------------------------------------
e02e26fe » rtomayko
2009-01-29 Add FAQ
193
194 Try starting Thin with the `--debug` argument:
195
196 thin --debug --rackup config.ru start
197
198 That should give you an exception and backtrace on `stderr`.
199
7c3487fc » rtomayko
2009-02-26 Fix TOC/anchor link in FAQ
200 How do I send Email from Sinatra? {#email}
f66ee558 » sr
2009-02-16 Table of content on FAQ
201 ---------------------------------
e02e26fe » rtomayko
2009-01-29 Add FAQ
202
420b8b1a » strand
2011-11-23 Fixed link to Pony. Noticed link to Reloader is broken, but uncertain…
203 How about a [Pony](http://adam.heroku.com/past/2008/11/2/pony_the_express_way_to_send_email_from_ruby/)
e02e26fe » rtomayko
2009-01-29 Add FAQ
204 (`sudo gem install pony`):
205
206 require 'pony'
207 post '/signup' do
208 Pony.mail :to => 'you@example.com',
939096d8 » Etienne Vallette d'Osia
2010-01-06 fix faq style
209 :from => 'me@example.com',
210 :subject => 'Howdy, Partna!'
e02e26fe » rtomayko
2009-01-29 Add FAQ
211 end
212
213 You can even use templates to render the body. In `email.erb`:
214
215 Good day <%= params[:name] %>,
216
217 Thanks for my signing my guestbook. You're a doll.
218
219 Frank
220
221 And in `mailerapp.rb`:
222
223 post '/guestbook/sign' do
224 Pony.mail :to => params[:email],
939096d8 » Etienne Vallette d'Osia
2010-01-06 fix faq style
225 :from => "me@example.com",
226 :subject => "Thanks for signing my guestbook, #{params[:name]}!",
227 :body => erb(:email)
e02e26fe » rtomayko
2009-01-29 Add FAQ
228 end
229
f66ee558 » sr
2009-02-16 Table of content on FAQ
230 How do I escape html? {#escape_html}
231 ---------------------
b2de8f23 » beenimble
2009-02-09 added FAQ on how to escape html
232
233 Include [Rack::Utils](http://rack.rubyforge.org/doc/classes/Rack/Utils.html)
234 in your helpers and create an `h` alias as follows:
235
236 helpers do
237 include Rack::Utils
25c5ec45 » Mehonoshin
2012-04-29 Fix error at escape html FAQ block
238 alias_method :h, :escape
b2de8f23 » beenimble
2009-02-09 added FAQ on how to escape html
239 end
240
241 Now you can escape html in your templates like this:
242
243 <%= h scary_output %>
244
fc048769 » cschneid
2009-02-11 Fix my name. I'm so vain.
245 Thanks to [Chris Schneider](http://www.gittr.com/index.php/archive/using-rackutils-in-sinatra-escape_html-h-in-rails/)
b2de8f23 » beenimble
2009-02-09 added FAQ on how to escape html
246 for the tip!
247
c78606b8 » trevorturk
2011-05-11 Add a section to the FAQ about automatic html escaping with erubis.
248 How do I automatically escape html? {#auto_escape_html}
249 ---------------------
250
ef42ce5d » trevorturk
2011-05-12 Expand on automatic html escaping with erubis.
251 Require [Erubis](http://rubygems.org/gems/erubis) and set `escape_html` to `true`:
c78606b8 » trevorturk
2011-05-11 Add a section to the FAQ about automatic html escaping with erubis.
252
253 require 'erubis'
254 set :erubis, :escape_html => true
255
ef42ce5d » trevorturk
2011-05-12 Expand on automatic html escaping with erubis.
256 Then, any templates rendered with Erubis will be automatically escaped:
257
258 get '/' do
259 erubis :index
260 end
261
262 Read more on the [Tilt Google Group](https://groups.google.com/forum/#!topic/tiltrb/PPm-sMz6Swc) and see [this example app](http://flowcoder.com/177) for details.
c78606b8 » trevorturk
2011-05-11 Add a section to the FAQ about automatic html escaping with erubis.
263
e7e72222 » sr
2009-02-28 FAQ: AR migrations
264 How do I use ActiveRecord migrations? {#ar-migrations}
265 -------------------------------------
266
267 From [Adam Wiggins's blog](http://adam.blog.heroku.com/past/2009/2/28/activerecord_migrations_outside_rails/):
268
269 > To use ActiveRecord’s migrations with Sinatra (or other non-Rails project),
270 > add the following to your Rakefile:
271 >
272 > namespace :db do
273 > desc "Migrate the database"
939096d8 » Etienne Vallette d'Osia
2010-01-06 fix faq style
274 > task(:migrate => :environment) do
e7e72222 » sr
2009-02-28 FAQ: AR migrations
275 > ActiveRecord::Base.logger = Logger.new(STDOUT)
276 > ActiveRecord::Migration.verbose = true
277 > ActiveRecord::Migrator.migrate("db/migrate")
278 > end
279 > end
280 >
281 > This assumes you have a task called `:environment` which loads your app’s
282 > environment (requires the right files, sets up the database connection, etc).
283 >
284 > Now you can create a directory called `db/migrate` and fill in your
285 > migrations. I usually call the first one `001_init.rb`.
286 > (I prefer the old sequential method for numbering migrations vs. the
287 > datetime method used since Rails 2.1, but either will work.)
288
289
f66ee558 » sr
2009-02-16 Table of content on FAQ
290 How do I use HTTP authentication? {#auth}
291 ---------------------------------
1601af3c » karmi
2009-02-11 Add FAQ item about testing HTTP Auth (Basic)
292
eae592a8 » karmi
2009-02-11 Add FAQ item about using HTTP authentication in Sinatra
293 You have at least two options for implementing basic access authentication (Basic HTTP Auth) in your application.
294
295 I. When you want to protect all requests in the application, simply put Rack::Auth::Basic middleware in the request processing chain by the `use` directive:
296
297 require 'rubygems'
298 require 'sinatra'
299
93772307 » alexgb
2011-01-12 Syntax error in FAQ page – extra comma.
300 use Rack::Auth::Basic, "Restricted Area" do |username, password|
eae592a8 » karmi
2009-02-11 Add FAQ item about using HTTP authentication in Sinatra
301 [username, password] == ['admin', 'admin']
302 end
303
304 get '/' do
305 "You're welcome"
306 end
307
308 get '/foo' do
309 "You're also welcome"
310 end
311
312 II. When you want to protect only certain URLs in the application, or want the authorization to be more complex, you may use something like this:
313
314 require 'rubygems'
315 require 'sinatra'
316
317 helpers do
318
319 def protected!
5d927836 » akahn
2010-01-29 Fix indentation in example basic auth helper in FAQ.
320 unless authorized?
13859288 » qmx
2011-01-02 Added Realm for HTTP Basic Authentication example
321 response['WWW-Authenticate'] = %(Basic realm="Restricted Area")
939096d8 » Etienne Vallette d'Osia
2010-01-06 fix faq style
322 throw(:halt, [401, "Not authorized\n"])
5d927836 » akahn
2010-01-29 Fix indentation in example basic auth helper in FAQ.
323 end
eae592a8 » karmi
2009-02-11 Add FAQ item about using HTTP authentication in Sinatra
324 end
325
326 def authorized?
327 @auth ||= Rack::Auth::Basic::Request.new(request.env)
328 @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ['admin', 'admin']
329 end
330
331 end
332
333 get '/' do
334 "Everybody can see this page"
335 end
336
337 get '/protected' do
338 protected!
339 "Welcome, authenticated client"
340 end
341
342
f66ee558 » sr
2009-02-16 Table of content on FAQ
343 How do I test HTTP authentication? {#test_http_auth}
344 ----------------------------------
eae592a8 » karmi
2009-02-11 Add FAQ item about using HTTP authentication in Sinatra
345
fa9bbef1 » karmi
2010-12-23 Cleaned up and corrected F.A.Q. section on testing HTTP Auth
346 Assuming you have this simple implementation of HTTP authentication in your `application.rb`:
1601af3c » karmi
2009-02-11 Add FAQ item about testing HTTP Auth (Basic)
347
348 require 'rubygems'
349 require 'sinatra'
350
351 use Rack::Auth::Basic do |username, password|
352 [username, password] == ['admin', 'admin']
353 end
354
355 get '/protected' do
356 "You're welcome"
357 end
358
fa9bbef1 » karmi
2010-12-23 Cleaned up and corrected F.A.Q. section on testing HTTP Auth
359 You can test it like this with [_Rack::Test_](https://github.com/brynary/rack-test):
360
361 ENV['RACK_ENV'] = 'test'
1601af3c » karmi
2009-02-11 Add FAQ item about testing HTTP Auth (Basic)
362
363 require 'rubygems'
fa9bbef1 » karmi
2010-12-23 Cleaned up and corrected F.A.Q. section on testing HTTP Auth
364 require 'test/unit'
365 require 'rack/test'
366
1601af3c » karmi
2009-02-11 Add FAQ item about testing HTTP Auth (Basic)
367 require 'application'
368
369 class ApplicationTest < Test::Unit::TestCase
fa9bbef1 » karmi
2010-12-23 Cleaned up and corrected F.A.Q. section on testing HTTP Auth
370 include Rack::Test::Methods
371
372 def app
373 Sinatra::Application
374 end
1601af3c » karmi
2009-02-11 Add FAQ item about testing HTTP Auth (Basic)
375
376 def test_without_authentication
377 get '/protected'
fa9bbef1 » karmi
2010-12-23 Cleaned up and corrected F.A.Q. section on testing HTTP Auth
378 assert_equal 401, last_response.status
1601af3c » karmi
2009-02-11 Add FAQ item about testing HTTP Auth (Basic)
379 end
380
381 def test_with_bad_credentials
fa9bbef1 » karmi
2010-12-23 Cleaned up and corrected F.A.Q. section on testing HTTP Auth
382 authorize 'bad', 'boy'
383 get '/protected'
384 assert_equal 401, last_response.status
1601af3c » karmi
2009-02-11 Add FAQ item about testing HTTP Auth (Basic)
385 end
386
387 def test_with_proper_credentials
fa9bbef1 » karmi
2010-12-23 Cleaned up and corrected F.A.Q. section on testing HTTP Auth
388 authorize 'admin', 'admin'
389 get '/protected'
390 assert_equal 200, last_response.status
391 assert_equal "You're welcome", last_response.body
1601af3c » karmi
2009-02-11 Add FAQ item about testing HTTP Auth (Basic)
392 end
393 end
394
fa9bbef1 » karmi
2010-12-23 Cleaned up and corrected F.A.Q. section on testing HTTP Auth
395
e02e26fe » rtomayko
2009-01-29 Add FAQ
396 <!--
397
398 ### <a id='queue' href='#queue'>How do I process jobs in the background?</a>
399 ### <a id='auth' href='#auth'>How do I process file uploads?</a>
400
401 -->
Something went wrong with that request. Please try again.