Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 350 lines (208 sloc) 6.518 kb
df800b5 Docs are started
Blake Mizerany authored
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
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
73
047edc6 update README with Static help
Blake Mizerany authored
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
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
127 === Erb
128
129 This works like Haml except you use <tt>erb</tt> instead of <tt>haml</tt>
130
1f20499 getting mare advanced with to_result
Blake Mizerany authored
131 === Builder
132
133 See Sinatra::Builder
134
df800b5 Docs are started
Blake Mizerany authored
135 = Helpers
136
137 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.
138
139 Example:
140
141 helpers do
142
143 def bar(name)
144 "#{name}bar"
145 end
146
147 end
1776a80 Added Version and Docs
Blake Mizerany authored
148
149 get '/:name' do
150 bar(params[:name])
151 end
df800b5 Docs are started
Blake Mizerany authored
152
153 = Before filters
154
1776a80 Added Version and Docs
Blake Mizerany authored
155 These are run in Sinatra::EventContext
156
df800b5 Docs are started
Blake Mizerany authored
157 before do
158 .. this code will run before each event ..
159 end
160
161 = Halt!
162
163 To immediately stop a request during a before filter or event use:
164
165 throw :halt
166
167 === Variations
168
169 Set the body to the result of a helper method
170
171 throw :halt, :helper_method
172
173 Set the body to the result of a helper method after sending it parameters from the local scope
174
175 throw :halt, [:helper_method, foo, bar]
176
177 Set the body to a simple string
178
179 throw :halt, 'this will be the body'
180
181 Set status then the body
182
183 throw :halt, [401, 'go away!']
184
185 Set the status then call a helper method with params from local scope
186
187 throw :halt, [401, [:helper_method, foo, bar]]
188
189 Run a proc inside the Sinatra::EventContext instance and set the body to the result
190
191 throw :halt, lambda { puts 'In a proc!'; 'I just wrote to $stdout!' }
192
193 Create you own to_result
194
195 class MyResultObject
196 def to_result(event_context, *args)
197 event_context.body = 'This will be the body!
198 end
199 end
200
201 get '/' do
202 throw :halt, MyResultObject.new
203 end
204
205 Get the gist? If you want more fun with this then checkout <tt>to_result</tt> on Array, Symbol, Fixnum, NilClass.
206
1776a80 Added Version and Docs
Blake Mizerany authored
207 = Configuration & Re-loading
208
209 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.
210
211 All environments:
212
213 configure do
214
215 end
216
217 Production
218
219 configure :production do
220
221 end
222
223 Two at a time:
224
225 configure :production, :test do
226
227 end
228
229 This is also really nifty for error handling.
230
231 = Error handling
232
233 === Not Found
234
235 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.)
236
237 Whenever NotFound is raised this will be called
238
239 not_found do
240 'This is nowhere to be found'
241 end
242
243 === Error
244
245 error do
246 # this is where the error is stored for you to grab
247 name = env['sinatra.error'].class.name
248 'ah shizzle! ' + name
249 end
250
251 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:
252
253 configure :production do
254
255 not_found do
256 "We're so sorry, but we don't what this is"
257 end
258
259 error do
260 "Something really nasty happened. We're on it!"
261 end
262
263 end
264
265 = Testing
266
267 === Test/Unit
268
269 require 'my_sinatra_app'
270 require 'sinatra/test/unit'
271
272 class MyAppTest < Test::Unit::TestCase
273
274 def test_my_default
275 get_it '/'
276 assert_equal 'My Default Page!', @response.body
277 end
278
279 def test_with_agent
280 get_it '/', :agent => 'Songbird'
281 assert_equal 'You're in Songbird!', @response.body
282 end
283
284 ...
285
286 end
287
288 === Test/Spec
289
290 require 'my_sinatra_app'
291 require 'sinatra/test/spec'
292
293 context 'My app'
294
295 should "show a default page" do
296 get_it '/'
297 should.be.ok
298 @response.body.should.equal 'My Default Page!'
299 end
300 ...
301
302 end
303
304 == Test helpers
305
306 See Sinatra::Test::Methods
307
308 = Irb
309
310 This will be back in soon
311
312 = Command line
313
314 Run your sinatra file like:
315
316 ruby myapp.rb [options]
317
318 Options are:
319
320 -h # help
321 -p # set the port (default is 4567)
322 -e # set the environment (default is development)
323 -x # turn on the mutext lock (default is off)
324
325 = Contribute
326
327 cd where/you/keep/your/projects
328 git clone git://github.com/bmizerany/sinatra.git
329 cd your_project
330 ln -s ../sinatra/
331
332 at the top of your sinatra.rb file
333
334 $:.unshift File.dirname(__FILE__) + '/sinatra/lib'
335 require 'sinatra'
336
337 get '/about' do
338 "I'm running on Version " + Sinatra::Version.combined
339 end
340
341
342
343
344
345
346
347
df800b5 Docs are started
Blake Mizerany authored
348
349
Something went wrong with that request. Please try again.