Skip to content
Newer
Older
100644 419 lines (250 sloc) 7.32 KB
df800b5 Docs are started
Blake Mizerany authored Mar 24, 2008
1 = Sinatra
2
3 Sinatra a DSL for quickly creating web-applications in Ruby with minimal effort.
4
5 = Sample app:
6
7 # myapp.rb
8
9 require 'rubygems'
10 require 'sinatra'
11
12 get '/' do
13 'Hello world!'
14 end
15
16 Ruby this as <tt>ruby myapp.rb</tt> and view at <tt>http://localhost:4567</tt>
17
18 = RESTful
19
20 get '/' do
21 .. show things ..
22 end
23
24 post '/' do
25 .. create something ..
26 end
27
28 put '/' do
29 .. update something ..
30 end
31
32 delete '/' do
33 .. annihilate something ..
34 end
1776a80 Added Version and Docs
Blake Mizerany authored Mar 24, 2008
35
36 head '/' do
37
38 end
39
40 NOTE: <tt>put</tt> and <tt>delete</tt> are triggered when a <tt>_method</tt> param is set to PUT or DELETE and the HTTP_REQUEST_METHOD is a POST
41
42 = Routes
43
44 NOTE: Routes are looked up in order of declaration
45
46 Simple
47
48 get '/hi' do
49 ...
50 end
51
52 With params
53
54 get '/:name' do
55 # matches /sinatra and the like and sets params[:name]
56 end
57
58 Splat'n
59
60 get '/message/*' do
61 # matches /message/1/2/3/4/5
62 end
63
64 Get an agent!
65
66 get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
67 "You're using Songbird version #{params[:agent][0]}"
68 end
69
70 get '/foo' do
71 # matches non-songbird browsers
72 end
df800b5 Docs are started
Blake Mizerany authored Mar 25, 2008
73
047edc6 update README with Static help
Blake Mizerany authored Mar 26, 2008
74 = Static files
75
76 Put all of your static content in the ./public directory
77
78 root
79 \ public
80
81 If a file exists that maps to the REQUEST_PATH then it is served and the request end; Sinatra will look for and event that matches the path otherwise
82
df800b5 Docs are started
Blake Mizerany authored Mar 25, 2008
83 = Views (if you need MVC)
84
85 All views are looked up in:
86
87 root
88 | - views/
89
90
91 == Templates
92
93 === Haml/Sass
94
95 get '/' do
96 haml :index
97 end
98
99 This will render <tt>./views/index.haml</tt>
100
101 === Inline
102
103 get '/' do
104 haml '%div.title Hello World'
105 end
106
107 This will render the inlined template string
108
109 === Accessing Variables
110
111 Templates are rendered in the context the current Sinatra::EventContext. This means you get all instance/class variables and methods it has access to.
112
113 get '/:id' do
114 @foo = Foo.find(params[:id])
115 haml '%h1== @foo.name'
116 end
117
118 Send local objects like:
119
120 get '/:id' do
121 localvar = Foo.find(params[:id])
122 haml '%h1== localvar.name', :locals => { :localvar => localvar }
123 end
124
125 This is more ideal for rendering templates as partials from within templates
126
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored Mar 29, 2008
127 == In file templates
128
129 This one is cool:
130
131 get '/' do
132 haml :index
133 end
134
135 use_in_file_templates!
136
137 __END__
138
139 ## layout
140 X
141 = yield
142 X
143
144 ## index
145 %div.title Hello world!!!!!
146
147 Try it!
148
149 = You can do this too but it's not as cool
150
151 template :layout do
152 "X\n=yield\nX"
153 end
154
155 template :index do
156 '%div.title Hello World!'
157 end
158
159 get '/' do
160 haml :index
161 end
162
df800b5 Docs are started
Blake Mizerany authored Mar 25, 2008
163 === Erb
164
165 This works like Haml except you use <tt>erb</tt> instead of <tt>haml</tt>
166
1f20499 getting mare advanced with to_result
Blake Mizerany authored Mar 24, 2008
167 === Builder
168
169 See Sinatra::Builder
170
df800b5 Docs are started
Blake Mizerany authored Mar 25, 2008
171 = Helpers
172
173 It is ill-advised to create helpers on (main). Use the handy <tt>helpers</tt> to install helper methods on Sinatra::EventContext for use inside events and templates.
174
175 Example:
176
177 helpers do
178
179 def bar(name)
180 "#{name}bar"
181 end
182
183 end
1776a80 Added Version and Docs
Blake Mizerany authored Mar 25, 2008
184
185 get '/:name' do
186 bar(params[:name])
187 end
df800b5 Docs are started
Blake Mizerany authored Mar 25, 2008
188
189 = Before filters
190
1776a80 Added Version and Docs
Blake Mizerany authored Mar 25, 2008
191 These are run in Sinatra::EventContext
192
df800b5 Docs are started
Blake Mizerany authored Mar 25, 2008
193 before do
194 .. this code will run before each event ..
195 end
196
197 = Halt!
198
199 To immediately stop a request during a before filter or event use:
200
201 throw :halt
202
203 === Variations
204
205 Set the body to the result of a helper method
206
207 throw :halt, :helper_method
208
209 Set the body to the result of a helper method after sending it parameters from the local scope
210
211 throw :halt, [:helper_method, foo, bar]
212
213 Set the body to a simple string
214
215 throw :halt, 'this will be the body'
216
217 Set status then the body
218
219 throw :halt, [401, 'go away!']
220
221 Set the status then call a helper method with params from local scope
222
223 throw :halt, [401, [:helper_method, foo, bar]]
224
225 Run a proc inside the Sinatra::EventContext instance and set the body to the result
226
227 throw :halt, lambda { puts 'In a proc!'; 'I just wrote to $stdout!' }
228
229 Create you own to_result
230
231 class MyResultObject
232 def to_result(event_context, *args)
233 event_context.body = 'This will be the body!
234 end
235 end
236
237 get '/' do
238 throw :halt, MyResultObject.new
239 end
240
241 Get the gist? If you want more fun with this then checkout <tt>to_result</tt> on Array, Symbol, Fixnum, NilClass.
242
1776a80 Added Version and Docs
Blake Mizerany authored Mar 25, 2008
243 = Configuration & Re-loading
244
245 Sinatra supports multiple environments and re-loading. Re-loading happens on every request when in :development. Wrap your configurations in <tt>configure</tt> (i.e. Database connections, Constants, etc.) to protect them from re-loading and to only work in certain environments.
246
247 All environments:
248
249 configure do
250
251 end
252
253 Production
254
255 configure :production do
256
257 end
258
259 Two at a time:
260
261 configure :production, :test do
262
263 end
264
265 This is also really nifty for error handling.
266
267 = Error handling
268
269 === Not Found
270
271 Remember: These are run inside the Sinatra::EventContext which means you get all the goodies is has to offer (i.e. haml, erb, :halt, etc.)
272
273 Whenever NotFound is raised this will be called
274
275 not_found do
276 'This is nowhere to be found'
277 end
278
279 === Error
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored Mar 29, 2008
280
281 By default +error+ will catch Sinatra::ServerError
282
283 Sinatra will pass you the error via the 'sinatra.error' in request.env
284
1776a80 Added Version and Docs
Blake Mizerany authored Mar 25, 2008
285 error do
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored Mar 29, 2008
286 'Sorry there was a nasty error - ' + request.env['sinatra.error'].name
287 end
288
289 Custom error mapping:
290
291 error MyCustomError do
292 'So what happened was...' + request.env['sinatra.env'].message
1776a80 Added Version and Docs
Blake Mizerany authored Mar 25, 2008
293 end
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored Mar 29, 2008
294
295 then if this happens:
296
297 get '/' do
298 raise MyCustomError, 'something bad'
299 end
300
301 you gets this:
302
303 So what happened was... something bad
304
305 one guess what this does ;)
306
307 not_found do
308 'I have no clue what you're looking for'
309 end
310
311 Try it!
312
1776a80 Added Version and Docs
Blake Mizerany authored Mar 25, 2008
313
314 Because Sinatra give you a default <tt>not_found</tt> and <tt>error</tt> do :production that are secure. If you want to customize only for :production but want to keep the friendly helper screens for :development then do this:
315
316 configure :production do
317
318 not_found do
319 "We're so sorry, but we don't what this is"
320 end
321
322 error do
323 "Something really nasty happened. We're on it!"
324 end
325
326 end
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored Mar 29, 2008
327
328 = Mime types
329
330 When using send_file or static files you may have mime types Sinatra doesn't understand. Use +mime+ in those cases.
331
332 mime :foo, 'text/foo'
1776a80 Added Version and Docs
Blake Mizerany authored Mar 25, 2008
333
334 = Testing
335
336 === Test/Unit
337
338 require 'my_sinatra_app'
339 require 'sinatra/test/unit'
340
341 class MyAppTest < Test::Unit::TestCase
342
343 def test_my_default
344 get_it '/'
345 assert_equal 'My Default Page!', @response.body
346 end
347
348 def test_with_agent
349 get_it '/', :agent => 'Songbird'
350 assert_equal 'You're in Songbird!', @response.body
351 end
352
353 ...
354
355 end
356
357 === Test/Spec
358
359 require 'my_sinatra_app'
360 require 'sinatra/test/spec'
361
362 context 'My app'
363
364 should "show a default page" do
365 get_it '/'
366 should.be.ok
83cba9c @bmizerany updated README with helpful tidbits
bmizerany authored Mar 29, 2008
367 body.should.equal 'My Default Page!'
1776a80 Added Version and Docs
Blake Mizerany authored Mar 25, 2008
368 end
369 ...
370
371 end
372
373 == Test helpers
374
375 See Sinatra::Test::Methods
376
377 = Irb
378
379 This will be back in soon
380
381 = Command line
382
383 Run your sinatra file like:
384
385 ruby myapp.rb [options]
386
387 Options are:
388
389 -h # help
390 -p # set the port (default is 4567)
391 -e # set the environment (default is development)
392 -x # turn on the mutext lock (default is off)
393
394 = Contribute
395
396 cd where/you/keep/your/projects
397 git clone git://github.com/bmizerany/sinatra.git
398 cd your_project
399 ln -s ../sinatra/
400
401 at the top of your sinatra.rb file
402
403 $:.unshift File.dirname(__FILE__) + '/sinatra/lib'
404 require 'sinatra'
405
406 get '/about' do
407 "I'm running on Version " + Sinatra::Version.combined
408 end
409
410
411
412
413
414
415
416
df800b5 Docs are started
Blake Mizerany authored Mar 25, 2008
417
418
Something went wrong with that request. Please try again.