sinatra 1.4.0.c → 1.4.0.d

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of sinatra might be problematic. Click here for more details.

@@ -1,1816 +0,0 @@
1
- = Sinatra
2
- <i>注:本文档仅仅是英文版的翻译,会出现内容没有及时更新的情况发生。
3
- 如有不一致的地方,请以英文版为准。</i>
4
-
5
- Sinatra是一个基于Ruby语言,以最小精力为代价快速创建web应用为目的的{DSL}[http://en.wikipedia.org/wiki/Domain-specific_language](
6
- 领域专属语言):
7
-
8
- # myapp.rb
9
- require 'sinatra'
10
-
11
- get '/' do
12
- 'Hello world!'
13
- end
14
-
15
- 安装gem然后运行:
16
-
17
- gem install sinatra
18
- ruby myapp.rb
19
-
20
- 在该地址查看: http://localhost:4567
21
-
22
- 推荐同时运行<tt>gem install thin</tt>,Sinatra会优先选择thin作为服务器。
23
-
24
- == 路由
25
-
26
- 在Sinatra中,一个路由是一个HTTP方法与URL匹配范式的配对。
27
- 每个路由都与一个代码块关联:
28
-
29
- get '/' do
30
- .. 显示一些事物 ..
31
- end
32
-
33
- post '/' do
34
- .. 创建一些事物 ..
35
- end
36
-
37
- put '/' do
38
- .. 更新一些事物 ..
39
- end
40
-
41
- delete '/' do
42
- .. 消灭一些事物 ..
43
- end
44
-
45
- options '/' do
46
- .. 满足一些事物 ..
47
- end
48
-
49
- 路由按照它们被定义的顺序进行匹配。
50
- 第一个与请求匹配的路由会被调用。
51
-
52
- 路由范式可以包括具名参数,可通过<tt>params</tt>哈希表获得:
53
-
54
- get '/hello/:name' do
55
- # 匹配 "GET /hello/foo" 和 "GET /hello/bar"
56
- # params[:name] 的值是 'foo' 或者 'bar'
57
- "Hello #{params[:name]}!"
58
- end
59
-
60
- 你同样可以通过代码块参数获得具名参数:
61
-
62
- get '/hello/:name' do |n|
63
- "Hello #{n}!"
64
- end
65
-
66
- 路由范式也可以包含通配符参数,
67
- 可以通过<tt>params[:splat]</tt> 数组获得。
68
-
69
- get '/say/*/to/*' do
70
- # 匹配 /say/hello/to/world
71
- params[:splat] # => ["hello", "world"]
72
- end
73
-
74
- get '/download/*.*' do
75
- # 匹配 /download/path/to/file.xml
76
- params[:splat] # => ["path/to/file", "xml"]
77
- end
78
-
79
- 通过正则表达式匹配的路由:
80
-
81
- get %r{/hello/([\w]+)} do
82
- "Hello, #{params[:captures].first}!"
83
- end
84
-
85
- 或者使用代码块参数:
86
-
87
- get %r{/hello/([\w]+)} do |c|
88
- "Hello, #{c}!"
89
- end
90
-
91
- === 条件
92
-
93
- 路由也可以包含多样的匹配条件,比如user agent:
94
-
95
- get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
96
- "你正在使用Songbird,版本是 #{params[:agent][0]}"
97
- end
98
-
99
- get '/foo' do
100
- # 匹配除Songbird以外的浏览器
101
- end
102
-
103
- 其他可选的条件是 +host_name+ 和 +provides+:
104
-
105
- get '/', :host_name => /^admin\./ do
106
- "管理员区域,无权进入!"
107
- end
108
-
109
- get '/', :provides => 'html' do
110
- haml :index
111
- end
112
-
113
- get '/', :provides => ['rss', 'atom', 'xml'] do
114
- builder :feed
115
- end
116
-
117
- 你也可以很轻松地定义自己的条件:
118
-
119
- set(:probability) { |value| condition { rand <= value } }
120
-
121
- get '/win_a_car', :probability => 0.1 do
122
- "You won!"
123
- end
124
-
125
- get '/win_a_car' do
126
- "Sorry, you lost."
127
- end
128
-
129
- === 返回值
130
-
131
- 路由代码块的返回值至少决定了返回给HTTP客户端的响应体,
132
- 或者至少决定了在Rack堆栈中的下一个中间件。
133
- 大多数情况下,将是一个字符串,就像上面的例子中的一样。
134
- 但是其他值也是可以接受的。
135
-
136
- 你可以返回任何对象,或者是一个合理的Rack响应,
137
- Rack body对象或者HTTP状态码:
138
-
139
- * 一个包含三个元素的数组: <tt>[状态 (Fixnum), 头 (Hash), 响应体 (回应 #each)]</tt>
140
- * 一个包含两个元素的数组: <tt>[状态 (Fixnum), 响应体 (回应 #each)]</tt>
141
- * 一个能够回应 <tt>#each</tt> ,只传回字符串的对象
142
- * 一个代表状态码的数字
143
-
144
- 那样,我们可以轻松的实现例如流式传输的例子:
145
-
146
- class Stream
147
- def each
148
- 100.times { |i| yield "#{i}\n" }
149
- end
150
- end
151
-
152
- get('/') { Stream.new }
153
-
154
- === 自定义路由匹配器
155
-
156
- 如上显示,Sinatra内置了对于使用字符串和正则表达式作为路由匹配的支持。
157
- 但是,它并没有只限于此。
158
- 你可以非常容易地定义你自己的匹配器:
159
-
160
- class AllButPattern
161
- Match = Struct.new(:captures)
162
-
163
- def initialize(except)
164
- @except = except
165
- @captures = Match.new([])
166
- end
167
-
168
- def match(str)
169
- @captures unless @except === str
170
- end
171
- end
172
-
173
- def all_but(pattern)
174
- AllButPattern.new(pattern)
175
- end
176
-
177
- get all_but("/index") do
178
- # ...
179
- end
180
-
181
- 请注意上面的例子可能超工程了,
182
- 因为它也可以用更简单的方式表述:
183
-
184
- get // do
185
- pass if request.path_info == "/index"
186
- # ...
187
- end
188
-
189
- 或者,使用消极向前查找:
190
-
191
- get %r{^(?!/index$)} do
192
- # ...
193
- end
194
-
195
- == 静态文件
196
-
197
- 静态文件是从 <tt>./public_folder</tt> 目录提供服务。你可以通过设置<tt>:public</tt>
198
- 选项设定一个不同的位置:
199
-
200
- set :public_folder, File.dirname(__FILE__) + '/static'
201
-
202
- 请注意public目录名并没有被包含在URL之中。文件
203
- <tt>./public/css/style.css</tt>是通过
204
- <tt>http://example.com/css/style.css</tt>地址访问的。
205
-
206
- == 视图 / 模板
207
-
208
- 模板被假定直接位于<tt>./views</tt>目录。
209
- 要使用不同的视图目录:
210
-
211
- set :views, File.dirname(__FILE__) + '/templates'
212
-
213
- 请记住一件非常重要的事情,你只可以通过符号引用模板,
214
- 即使它们在子目录下
215
- (在这种情况下,使用 <tt>:'subdir/template'</tt>)。
216
- 你必须使用一个符号,
217
- 因为渲染方法会直接地渲染任何传入的字符串。
218
-
219
- === Haml模板
220
-
221
- 需要引入 <tt>haml</tt> gem/library以渲染 HAML 模板:
222
-
223
- # 你需要在你的应用中引入 haml
224
- require 'haml'
225
-
226
- get '/' do
227
- haml :index
228
- end
229
-
230
- 渲染 <tt>./views/index.haml</tt>。
231
-
232
- {Haml的选项}[http://haml.info/docs/yardoc/file.HAML_REFERENCE.html#options]
233
- 可以通过Sinatra的配置全局设定,
234
- 参见 {选项和配置}[http://www.sinatrarb.com/configuration.html],
235
- 也可以个别的被覆盖。
236
-
237
- set :haml, {:format => :html5 } # 默认的Haml输出格式是 :xhtml
238
-
239
- get '/' do
240
- haml :index, :haml_options => {:format => :html4 } # 被覆盖,变成:html4
241
- end
242
-
243
-
244
- === Erb模板
245
-
246
- # 你需要在你的应用中引入 erb
247
- require 'erb'
248
-
249
- get '/' do
250
- erb :index
251
- end
252
-
253
- 渲染 <tt>./views/index.erb</tt>
254
-
255
- === Erubis
256
-
257
- 需要引入 <tt>erubis</tt> gem/library以渲染 erubis 模板:
258
-
259
- # 你需要在你的应用中引入 erubis
260
- require 'erubis'
261
-
262
- get '/' do
263
- erubis :index
264
- end
265
-
266
- 渲染 <tt>./views/index.erubis</tt>
267
-
268
- 使用Erubis代替Erb也是可能的:
269
-
270
- require 'erubis'
271
- Tilt.register :erb, Tilt[:erubis]
272
-
273
- get '/' do
274
- erb :index
275
- end
276
-
277
- 使用Erubis来渲染 <tt>./views/index.erb</tt>。
278
-
279
- === Builder 模板
280
-
281
- 需要引入 <tt>builder</tt> gem/library 以渲染 builder templates:
282
-
283
- # 需要在你的应用中引入builder
284
- require 'builder'
285
-
286
- get '/' do
287
- builder :index
288
- end
289
-
290
- 渲染 <tt>./views/index.builder</tt>。
291
-
292
- === Nokogiri 模板
293
-
294
- 需要引入 <tt>nokogiri</tt> gem/library 以渲染 nokogiri 模板:
295
-
296
- # 需要在你的应用中引入 nokogiri
297
- require 'nokogiri'
298
-
299
- get '/' do
300
- nokogiri :index
301
- end
302
-
303
- 渲染 <tt>./views/index.nokogiri</tt>。
304
-
305
- === Sass 模板
306
-
307
- 需要引入 <tt>haml</tt> 或者 <tt>sass</tt> gem/library 以渲染 Sass 模板:
308
-
309
- # 需要在你的应用中引入 haml 或者 sass
310
- require 'sass'
311
-
312
- get '/stylesheet.css' do
313
- sass :stylesheet
314
- end
315
-
316
- 渲染 <tt>./views/stylesheet.sass</tt>。
317
-
318
- {Sass 的选项}[http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#options]
319
- 可以通过Sinatra选项全局设定,
320
- 参考 {选项和配置(英文)}[http://www.sinatrarb.com/configuration.html],
321
- 也可以在个体的基础上覆盖。
322
-
323
- set :sass, {:style => :compact } # 默认的 Sass 样式是 :nested
324
-
325
- get '/stylesheet.css' do
326
- sass :stylesheet, :style => :expanded # 覆盖
327
- end
328
-
329
- === Scss 模板
330
-
331
- 需要引入 <tt>haml</tt> 或者 <tt>sass</tt> gem/library 来渲染 Scss templates:
332
-
333
- # 需要在你的应用中引入 haml 或者 sass
334
- require 'sass'
335
-
336
- get '/stylesheet.css' do
337
- scss :stylesheet
338
- end
339
-
340
- 渲染 <tt>./views/stylesheet.scss</tt>。
341
-
342
- {Scss的选项}[http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#options]
343
- 可以通过Sinatra选项全局设定,
344
- 参考 {选项和配置(英文)}[http://www.sinatrarb.com/configuration.html],
345
- 也可以在个体的基础上覆盖。
346
-
347
- set :scss, :style => :compact # default Scss style is :nested
348
-
349
- get '/stylesheet.css' do
350
- scss :stylesheet, :style => :expanded # overridden
351
- end
352
-
353
- === Less 模板
354
-
355
- 需要引入 <tt>less</tt> gem/library 以渲染 Less 模板:
356
-
357
- # 需要在你的应用中引入 less
358
- require 'less'
359
-
360
- get '/stylesheet.css' do
361
- less :stylesheet
362
- end
363
-
364
- 渲染 <tt>./views/stylesheet.less</tt>。
365
-
366
- === Liquid 模板
367
-
368
- 需要引入 <tt>liquid</tt> gem/library 来渲染 Liquid 模板:
369
-
370
- # 需要在你的应用中引入 liquid
371
- require 'liquid'
372
-
373
- get '/' do
374
- liquid :index
375
- end
376
-
377
- 渲染 <tt>./views/index.liquid</tt>。
378
-
379
- 因为你不能在Liquid 模板中调用 Ruby 方法 (除了 +yield+) ,
380
- 你几乎总是需要传递locals给它:
381
-
382
- liquid :index, :locals => { :key => 'value' }
383
-
384
- === Markdown 模板
385
-
386
- 需要引入 <tt>rdiscount</tt> gem/library 以渲染 Markdown 模板:
387
-
388
- # 需要在你的应用中引入rdiscount
389
- require "rdiscount"
390
-
391
- get '/' do
392
- markdown :index
393
- end
394
-
395
- 渲染 <tt>./views/index.markdown</tt>
396
- (+md+ 和 +mkd+ 也是合理的文件扩展名)。
397
-
398
- 在markdown中是不可以调用方法的,也不可以传递 locals给它。
399
- 你因此一般会结合其他的渲染引擎来使用它:
400
-
401
-
402
- erb :overview, :locals => { :text => markdown(:introduction) }
403
-
404
- 请注意你也可以从其他模板中调用 markdown 方法:
405
-
406
- %h1 Hello From Haml!
407
- %p= markdown(:greetings)
408
-
409
- 既然你不能在Markdown中调用Ruby,你不能使用Markdown编写的布局。
410
- 不过,使用其他渲染引擎作为模版的布局是可能的,
411
- 通过传递<tt>:layout_engine</tt>选项:
412
-
413
- get '/' do
414
- markdown :index, :layout_engine => :erb
415
- end
416
-
417
- 这将会渲染 <tt>./views/index.md</tt> 并使用
418
- <tt>./views/layout.erb</tt> 作为布局。
419
-
420
- 请记住你可以全局设定这个选项:
421
-
422
- set :markdown, :layout_engine => :haml, :layout => :post
423
-
424
- get '/' do
425
- markdown :index
426
- end
427
-
428
- 这将会渲染 <tt>./views/index.markdown</tt> (和任何其他的 Markdown
429
- 模版) 并使用 <tt>./views/post.haml</tt> 作为布局.
430
-
431
- 也可能使用BlueCloth而不是RDiscount来解析Markdown文件:
432
-
433
- require 'bluecloth'
434
-
435
- Tilt.register 'markdown', BlueClothTemplate
436
- Tilt.register 'mkd', BlueClothTemplate
437
- Tilt.register 'md', BlueClothTemplate
438
-
439
- get '/' do
440
- markdown :index
441
- end
442
-
443
- 使用BlueCloth来渲染 <tt>./views/index.md</tt> 。
444
-
445
- === Textile 模板
446
-
447
- 需要引入 <tt>RedCloth</tt> gem/library 以渲染 Textile 模板:
448
-
449
- # 在你的应用中引入redcloth
450
- require "redcloth"
451
-
452
- get '/' do
453
- textile :index
454
- end
455
-
456
- 渲染 <tt>./views/index.textile</tt>。
457
-
458
- 在textile中是不可以调用方法的,也不可以传递 locals给它。
459
- 你因此一般会结合其他的渲染引擎来使用它:
460
-
461
- erb :overview, :locals => { :text => textile(:introduction) }
462
-
463
- 请注意你也可以从其他模板中调用+textile+方法:
464
-
465
- %h1 Hello From Haml!
466
- %p= textile(:greetings)
467
-
468
- 既然你不能在Textile中调用Ruby,你不能使用Textile编写的布局。
469
- 不过,使用其他渲染引擎作为模版的布局是可能的,
470
- 通过传递<tt>:layout_engine</tt>选项:
471
-
472
- get '/' do
473
- textile :index, :layout_engine => :erb
474
- end
475
-
476
- 这将会渲染 <tt>./views/index.textile</tt> 并使用
477
- <tt>./views/layout.erb</tt> 作为布局。
478
-
479
- 请记住你可以全局设定这个选项:
480
-
481
- set :textile, :layout_engine => :haml, :layout => :post
482
-
483
- get '/' do
484
- textile :index
485
- end
486
-
487
- 这将会渲染 <tt>./views/index.textile</tt> (和任何其他的 Textile
488
- 模版) 并使用 <tt>./views/post.haml</tt> 作为布局.
489
-
490
- === RDoc 模板
491
-
492
- 需要引入 <tt>RDoc</tt> gem/library 以渲染RDoc模板:
493
-
494
- # 需要在你的应用中引入rdoc/markup/to_html
495
- require "rdoc"
496
- require "rdoc/markup/to_html"
497
-
498
- get '/' do
499
- rdoc :index
500
- end
501
-
502
- 渲染 <tt>./views/index.rdoc</tt>。
503
-
504
- 在rdoc中是不可以调用方法的,也不可以传递locals给它。
505
- 你因此一般会结合其他的渲染引擎来使用它:
506
-
507
- erb :overview, :locals => { :text => rdoc(:introduction) }
508
-
509
- 请注意你也可以从其他模板中调用+rdoc+方法:
510
-
511
- %h1 Hello From Haml!
512
- %p= rdoc(:greetings)
513
-
514
- 既然你不能在RDoc中调用Ruby,你不能使用RDoc编写的布局。
515
- 不过,使用其他渲染引擎作为模版的布局是可能的,
516
- 通过传递<tt>:layout_engine</tt>选项:
517
-
518
- get '/' do
519
- rdoc :index, :layout_engine => :erb
520
- end
521
-
522
- 这将会渲染 <tt>./views/index.rdoc</tt> 并使用
523
- <tt>./views/layout.erb</tt> 作为布局。
524
-
525
- 请记住你可以全局设定这个选项:
526
-
527
- set :rdoc, :layout_engine => :haml, :layout => :post
528
-
529
- get '/' do
530
- rdoc :index
531
- end
532
-
533
- 这将会渲染 <tt>./views/index.rdoc</tt> (和任何其他的 RDoc
534
- 模版) 并使用 <tt>./views/post.haml</tt> 作为布局.
535
-
536
- === Radius 模板
537
-
538
- 需要引入 <tt>radius</tt> gem/library 以渲染 Radius 模板:
539
-
540
- # 需要在你的应用中引入radius
541
- require 'radius'
542
-
543
- get '/' do
544
- radius :index
545
- end
546
-
547
- 渲染 <tt>./views/index.radius</tt>。
548
-
549
- 因为你不能在Radius 模板中调用 Ruby 方法 (除了 +yield+) ,
550
- 你几乎总是需要传递locals给它:
551
-
552
- radius :index, :locals => { :key => 'value' }
553
-
554
- === Markaby 模板
555
-
556
- 需要引入<tt>markaby</tt> gem/library以渲染Markaby模板:
557
-
558
- #需要在你的应用中引入 markaby
559
- require 'markaby'
560
-
561
- get '/' do
562
- markaby :index
563
- end
564
-
565
- 渲染 <tt>./views/index.mab</tt>。
566
-
567
- 你也可以使用嵌入的 Markaby:
568
-
569
- get '/' do
570
- markaby { h1 "Welcome!" }
571
- end
572
-
573
- === Slim 模板
574
-
575
- 需要引入 <tt>slim</tt> gem/library 来渲染 Slim 模板:
576
-
577
- # 需要在你的应用中引入 slim
578
- require 'slim'
579
-
580
- get '/' do
581
- slim :index
582
- end
583
-
584
- 渲染 <tt>./views/index.slim</tt>。
585
-
586
- === Creole 模板
587
-
588
- 需要引入 <tt>creole</tt> gem/library 来渲染 Creole 模板:
589
-
590
- # 需要在你的应用中引入 creole
591
- require 'creole'
592
-
593
- get '/' do
594
- creole :index
595
- end
596
-
597
- 渲染 <tt>./views/index.creole</tt>。
598
-
599
- === CoffeeScript 模板
600
-
601
- 需要引入 <tt>coffee-script</tt> gem/library 并至少满足下面条件一项
602
- 以执行Javascript:
603
-
604
- * +node+ (来自 Node.js) 在你的路径中
605
- * 你正在运行 OSX
606
- * +therubyracer+ gem/library
607
-
608
- 请察看 http://github.com/josh/ruby-coffee-script 获取更新的选项。
609
-
610
- 现在你可以渲染 CoffeeScript 模版了:
611
-
612
- # 需要在你的应用中引入coffee-script
613
- require 'coffee-script'
614
-
615
- get '/application.js' do
616
- coffee :application
617
- end
618
-
619
- 渲染 <tt>./views/application.coffee</tt>。
620
-
621
- === 嵌入模板字符串
622
-
623
- get '/' do
624
- haml '%div.title Hello World'
625
- end
626
-
627
- 渲染嵌入模板字符串。
628
-
629
- === 在模板中访问变量
630
-
631
- 模板和路由执行器在同样的上下文求值。
632
- 在路由执行器中赋值的实例变量可以直接被模板访问。
633
-
634
- get '/:id' do
635
- @foo = Foo.find(params[:id])
636
- haml '%h1= @foo.name'
637
- end
638
-
639
- 或者,显式地指定一个本地变量的哈希:
640
-
641
- get '/:id' do
642
- foo = Foo.find(params[:id])
643
- haml '%h1= foo.name', :locals => { :foo => foo }
644
- end
645
-
646
- 典型的使用情况是在别的模板中按照局部模板的方式来渲染。
647
-
648
-
649
- === 内联模板
650
-
651
- 模板可以在源文件的末尾定义:
652
-
653
- require 'sinatra'
654
-
655
- get '/' do
656
- haml :index
657
- end
658
-
659
- __END__
660
-
661
- @@ layout
662
- %html
663
- = yield
664
-
665
- @@ index
666
- %div.title Hello world!!!!!
667
-
668
- 注意:引入sinatra的源文件中定义的内联模板才能被自动载入。
669
- 如果你在其他源文件中有内联模板,
670
- 需要显式执行调用<tt>enable :inline_templates</tt>。
671
-
672
- === 具名模板
673
-
674
- 模板可以通过使用顶层 <tt>template</tt> 方法定义:
675
-
676
- template :layout do
677
- "%html\n =yield\n"
678
- end
679
-
680
- template :index do
681
- '%div.title Hello World!'
682
- end
683
-
684
- get '/' do
685
- haml :index
686
- end
687
-
688
- 如果存在名为"layout"的模板,该模板会在每个模板渲染的时候被使用。
689
- 你可以单独地通过传送 <tt>:layout => false</tt>来禁用,
690
- 或者通过<tt>set :haml, :layout => false</tt>来禁用他们。
691
-
692
- get '/' do
693
- haml :index, :layout => !request.xhr?
694
- end
695
-
696
- === 关联文件扩展名
697
-
698
- 为了关联一个文件扩展名到一个模版引擎,使用
699
- <tt>Tilt.register</tt>。比如,如果你喜欢使用
700
- +tt+ 作为Textile模版的扩展名,你可以这样做:
701
-
702
- Tilt.register :tt, Tilt[:textile]
703
-
704
- === 添加你自己的模版引擎
705
-
706
- 首先,通过Tilt注册你自己的引擎,然后创建一个渲染方法:
707
-
708
- Tilt.register :myat, MyAwesomeTemplateEngine
709
-
710
- helpers do
711
- def myat(*args) render(:myat, *args) end
712
- end
713
-
714
- get '/' do
715
- myat :index
716
- end
717
-
718
- 渲染 <tt>./views/index.myat</tt>。察看 https://github.com/rtomayko/tilt
719
- 来更多了解Tilt.
720
-
721
- == 过滤器
722
-
723
- 前置过滤器在每个请求前,在请求的上下文环境中被执行,
724
- 而且可以修改请求和响应。
725
- 在过滤器中设定的实例变量可以被路由和模板访问:
726
-
727
- before do
728
- @note = 'Hi!'
729
- request.path_info = '/foo/bar/baz'
730
- end
731
-
732
- get '/foo/*' do
733
- @note #=> 'Hi!'
734
- params[:splat] #=> 'bar/baz'
735
- end
736
-
737
- 后置过滤器在每个请求之后,在请求的上下文环境中执行,
738
- 而且可以修改请求和响应。
739
- 在前置过滤器和路由中设定的实例变量可以被后置过滤器访问:
740
-
741
- after do
742
- puts response.status
743
- end
744
-
745
- 请注意:除非你显式使用 +body+ 方法,而不是在路由中直接返回字符串,
746
- 消息体在后置过滤器是不可用的,
747
- 因为它在之后才会生成。
748
-
749
- 过滤器可以可选地带有范式,
750
- 只有请求路径满足该范式时才会执行:
751
-
752
- before '/protected/*' do
753
- authenticate!
754
- end
755
-
756
- after '/create/:slug' do |slug|
757
- session[:last_slug] = slug
758
- end
759
-
760
- 和路由一样,过滤器也可以带有条件:
761
-
762
- before :agent => /Songbird/ do
763
- # ...
764
- end
765
-
766
- after '/blog/*', :host_name => 'example.com' do
767
- # ...
768
- end
769
-
770
- == 辅助方法
771
-
772
- 使用顶层的 <tt>helpers</tt> 方法来定义辅助方法,
773
- 以便在路由处理器和模板中使用:
774
-
775
- helpers do
776
- def bar(name)
777
- "#{name}bar"
778
- end
779
- end
780
-
781
- get '/:name' do
782
- bar(params[:name])
783
- end
784
-
785
- === 使用 Sessions
786
-
787
- Session被用来在请求之间保持状态。如果被激活,每一个用户会话
788
- 对应有一个session哈希:
789
-
790
- enable :sessions
791
-
792
- get '/' do
793
- "value = " << session[:value].inspect
794
- end
795
-
796
- get '/:value' do
797
- session[:value] = params[:value]
798
- end
799
-
800
- 请注意 <tt>enable :sessions</tt> 实际上保存所有的数据在一个cookie之中。
801
- 这可能不会总是做你想要的(比如,保存大量的数据会增加你的流量)。
802
- 你可以使用任何的Rack session中间件,为了这么做,
803
- *不要*调用 <tt>enable :sessions</tt>,而是
804
- 按照自己的需要引入你的中间件:
805
-
806
- use Rack::Session::Pool, :expire_after => 2592000
807
-
808
- get '/' do
809
- "value = " << session[:value].inspect
810
- end
811
-
812
- get '/:value' do
813
- session[:value] = params[:value]
814
- end
815
-
816
- === 挂起
817
-
818
- 要想直接地停止请求,在过滤器或者路由中使用:
819
-
820
- halt
821
-
822
- 你也可以指定挂起时的状态码:
823
-
824
- halt 410
825
-
826
- 或者消息体:
827
-
828
- halt 'this will be the body'
829
-
830
- 或者两者;
831
-
832
- halt 401, 'go away!'
833
-
834
- 也可以带消息头:
835
-
836
- halt 402, {'Content-Type' => 'text/plain'}, 'revenge'
837
-
838
- === 让路
839
-
840
- 一个路由可以放弃处理,将处理让给下一个匹配的路由,使用 <tt>pass</tt>:
841
-
842
- get '/guess/:who' do
843
- pass unless params[:who] == 'Frank'
844
- 'You got me!'
845
- end
846
-
847
- get '/guess/*' do
848
- 'You missed!'
849
- end
850
-
851
- 路由代码块被直接退出,控制流继续前进到下一个匹配的路由。
852
- 如果没有匹配的路由,将返回404。
853
-
854
- === 触发另一个路由
855
-
856
- 有些时候,+pass+ 并不是你想要的,你希望得到的是另一个路由的结果
857
- 。简单的使用 +call+ 可以做到这一点:
858
-
859
- get '/foo' do
860
- status, headers, body = call env.merge("PATH_INFO" => '/bar')
861
- [status, headers, body.map(&:upcase)]
862
- end
863
-
864
- get '/bar' do
865
- "bar"
866
- end
867
-
868
- 请注意在以上例子中,你可以更加简化测试并增加性能,只要简单的移动
869
- <tt>"bar"</tt>到一个被<tt>/foo</tt>
870
- 和 <tt>/bar</tt>同时使用的helper。
871
-
872
- 如果你希望请求被发送到同一个应用,而不是副本,
873
- 使用 <tt>call!</tt> 而不是 <tt>call</tt>.
874
-
875
- 察看 Rack specification 如果你想更多了解 <tt>call</tt>.
876
-
877
- === 设定 消息体,状态码和消息头
878
-
879
- 通过路由代码块的返回值来设定状态码和消息体不仅是可能的,而且是推荐的。
880
- 但是,在某些场景中你可能想在作业流程中的特定点上设置消息体。
881
- 你可以通过 +body+ 辅助方法这么做。
882
- 如果你这样做了,
883
- 你可以在那以后使用该方法获得消息体:
884
-
885
- get '/foo' do
886
- body "bar"
887
- end
888
-
889
- after do
890
- puts body
891
- end
892
-
893
- 也可以传一个代码块给 +body+,它将会被Rack处理器执行(
894
- 这将可以被用来实现streaming,参见“返回值”)。
895
-
896
- 和消息体类似,你也可以设定状态码和消息头:
897
-
898
- get '/foo' do
899
- status 418
900
- headers \
901
- "Allow" => "BREW, POST, GET, PROPFIND, WHEN",
902
- "Refresh" => "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt"
903
- body "I'm a tea pot!"
904
- end
905
-
906
- 如同 +body+, 不带参数的 +headers+ 和 +status+ 可以用来访问
907
- 他们你的当前值.
908
-
909
- === 媒体类型
910
-
911
- 当使用 <tt>send_file</tt> 或者静态文件的场合,你的媒体类型可能
912
- Sinatra并不理解。使用 +mime_type+ 通过文件扩展名来注册它们:
913
-
914
- mime_type :foo, 'text/foo'
915
-
916
- 你也可以通过 +content_type+ 辅助方法使用:
917
-
918
- get '/' do
919
- content_type :foo
920
- "foo foo foo"
921
- end
922
-
923
- === 生成 URL
924
-
925
- 为了生成URL,你需要使用 +url+ 辅助方法,
926
- 例如,在Haml中:
927
-
928
- %a{:href => url('/foo')} foo
929
-
930
- 它会根据反向代理和Rack路由,如果有的话,来计算生成的URL。
931
-
932
- 这个方法还有一个别名 +to+ (见下面的例子).
933
-
934
- === 浏览器重定向
935
-
936
- 你可以通过 +redirect+ 辅助方法触发浏览器重定向:
937
-
938
- get '/foo' do
939
- redirect to('/bar')
940
- end
941
-
942
- 任何额外的参数都会被以 +halt+相同的方式来处理:
943
-
944
- redirect to('/bar'), 303
945
- redirect 'http://google.com', 'wrong place, buddy'
946
-
947
- 你可以方便的通过
948
- <tt>redirect back</tt>把用户重定向到来自的页面:
949
-
950
- get '/foo' do
951
- "<a href='/bar'>do something</a>"
952
- end
953
-
954
- get '/bar' do
955
- do_something
956
- redirect back
957
- end
958
-
959
- 为了传递参数给redirect,或者加入query:
960
-
961
- redirect to('/bar?sum=42')
962
-
963
- 或者使用session:
964
-
965
- enable :sessions
966
-
967
- get '/foo' do
968
- session[:secret] = 'foo'
969
- redirect to('/bar')
970
- end
971
-
972
- get '/bar' do
973
- session[:secret]
974
- end
975
-
976
- === 缓存控制
977
-
978
- 正确地设定消息头是恰当的HTTP缓存的基础。
979
-
980
- 你可以方便的设定 Cache-Control 消息头,像这样:
981
-
982
- get '/' do
983
- cache_control :public
984
- "cache it!"
985
- end
986
-
987
- 核心提示: 在前置过滤器中设定缓存.
988
-
989
- before do
990
- cache_control :public, :must_revalidate, :max_age => 60
991
- end
992
-
993
- 如果你正在用 +expires+ 辅助方法设定对应的消息头
994
- <tt>Cache-Control</tt> 会自动设定:
995
-
996
- before do
997
- expires 500, :public, :must_revalidate
998
- end
999
-
1000
- 为了合适地使用缓存,你应该考虑使用 +etag+ 和 +last_modified+方法。.
1001
- 推荐在执行繁重任务*之前*使用这些helpers,
1002
- 他们会立刻发送响应,如果客户端在缓存中已经有了当前版本。
1003
-
1004
- get '/article/:id' do
1005
- @article = Article.find params[:id]
1006
- last_modified @article.updated_at
1007
- etag @article.sha1
1008
- erb :article
1009
- end
1010
-
1011
- 使用
1012
- {weak ETag}[http://en.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation]
1013
- 也是有可能的:
1014
-
1015
- etag @article.sha1, :weak
1016
-
1017
- 这些辅助方法并不会为你做任何缓存,而是将必要的信息传送给你的缓存
1018
- 如果你在寻找缓存的快速解决方案,试试
1019
- {rack-cache}[https://github.com/rtomayko/rack-cache]:
1020
-
1021
- require "rack/cache"
1022
- require "sinatra"
1023
-
1024
- use Rack::Cache
1025
-
1026
- get '/' do
1027
- cache_control :public, :max_age => 36000
1028
- sleep 5
1029
- "hello"
1030
- end
1031
-
1032
- === 发送文件
1033
-
1034
- 为了发送文件,你可以使用 <tt>send_file</tt> 辅助方法:
1035
-
1036
- get '/' do
1037
- send_file 'foo.png'
1038
- end
1039
-
1040
- 也可以带一些选项:
1041
-
1042
- send_file 'foo.png', :type => :jpg
1043
-
1044
- 可用的选项有:
1045
-
1046
- [filename]
1047
- 响应中的文件名,默认是真实文件的名字。
1048
-
1049
- [last_modified]
1050
- Last-Modified 消息头的值,默认是文件的mtime(修改时间)。
1051
-
1052
- [type]
1053
- 使用的内容类型,如果没有会从文件扩展名猜测。
1054
-
1055
- [disposition]
1056
- 用于 Content-Disposition,可能的包括: +nil+ (默认),
1057
- <tt>:attachment</tt> 和 <tt>:inline</tt>
1058
-
1059
- [length]
1060
- Content-Length 的值,默认是文件的大小。
1061
-
1062
- 如果Rack处理器支持,Ruby进程除streaming以外的方式会被使用。
1063
- 如果你使用这个辅助方法,
1064
- Sinatra会自动处理range请求。
1065
-
1066
- === 访问请求对象
1067
-
1068
- 传入的请求对象可以在请求层(过滤器,路由,错误处理)
1069
- 通过 <tt>request</tt> 方法被访问:
1070
-
1071
- # 在 http://example.com/example 上运行的应用
1072
- get '/foo' do
1073
- request.body # 被客户端设定的请求体(见下)
1074
- request.scheme # "http"
1075
- request.script_name # "/example"
1076
- request.path_info # "/foo"
1077
- request.port # 80
1078
- request.request_method # "GET"
1079
- request.query_string # ""
1080
- request.content_length # request.body的长度
1081
- request.media_type # request.body的媒体类型
1082
- request.host # "example.com"
1083
- request.get? # true (其他动词也具有类似方法)
1084
- request.form_data? # false
1085
- request["SOME_HEADER"] # SOME_HEADER header的值
1086
- request.referrer # 客户端的referrer 或者 '/'
1087
- request.user_agent # user agent (被 :agent 条件使用)
1088
- request.cookies # 浏览器 cookies 哈希
1089
- request.xhr? # 这是否是ajax请求?
1090
- request.url # "http://example.com/example/foo"
1091
- request.path # "/example/foo"
1092
- request.ip # 客户端IP地址
1093
- request.secure? # false(如果是ssl则为true)
1094
- request.forwarded? # true (如果是运行在反向代理之后)
1095
- request.env # Rack中使用的未处理的env哈希
1096
- end
1097
-
1098
- 一些选项,例如 <tt>script_name</tt> 或者 <tt>path_info</tt>
1099
- 也是可写的:
1100
-
1101
- before { request.path_info = "/" }
1102
-
1103
- get "/" do
1104
- "all requests end up here"
1105
- end
1106
-
1107
- <tt>request.body</tt> 是一个IO或者StringIO对象:
1108
-
1109
- post "/api" do
1110
- request.body.rewind # 如果已经有人读了它
1111
- data = JSON.parse request.body.read
1112
- "Hello #{data['name']}!"
1113
- end
1114
-
1115
- === 附件
1116
-
1117
- 你可以使用 +attachment+ 辅助方法来告诉浏览器响应
1118
- 应当被写入磁盘而不是在浏览器中显示。
1119
-
1120
- get '/' do
1121
- attachment
1122
- "store it!"
1123
- end
1124
-
1125
- 你也可以传递一个文件名:
1126
-
1127
- get '/' do
1128
- attachment "info.txt"
1129
- "store it!"
1130
- end
1131
-
1132
- === 查找模板文件
1133
-
1134
- <tt>find_template</tt> 辅助方法被用于在渲染时查找模板文件:
1135
-
1136
- find_template settings.views, 'foo', Tilt[:haml] do |file|
1137
- puts "could be #{file}"
1138
- end
1139
-
1140
- 这并不是很有用。但是在你需要重载这个方法
1141
- 来实现你自己的查找机制的时候有用。
1142
- 比如,如果你想支持多于一个视图目录:
1143
-
1144
- set :views, ['views', 'templates']
1145
-
1146
- helpers do
1147
- def find_template(views, name, engine, &block)
1148
- Array(views).each { |v| super(v, name, engine, &block) }
1149
- end
1150
- end
1151
-
1152
- 另一个例子是为不同的引擎使用不同的目录:
1153
-
1154
- set :views, :sass => 'views/sass', :haml => 'templates', :default => 'views'
1155
-
1156
- helpers do
1157
- def find_template(views, name, engine, &block)
1158
- _, folder = views.detect { |k,v| engine == Tilt[k] }
1159
- folder ||= views[:default]
1160
- super(folder, name, engine, &block)
1161
- end
1162
- end
1163
-
1164
- 你可以很容易地包装成一个扩展然后与他人分享!
1165
-
1166
- 请注意 <tt>find_template</tt> 并不会检查文件真的存在,
1167
- 而是对任何可能的路径调用给入的代码块。这并不会带来性能问题,
1168
- 因为 +render+ 会在找到文件的时候马上使用 +break+ 。
1169
- 同样的,模板的路径(和内容)会在除development mode以外的场合
1170
- 被缓存。你应该时刻提醒自己这一点,
1171
- 如果你真的想写一个非常疯狂的方法。
1172
-
1173
- == 配置
1174
-
1175
- 运行一次,在启动的时候,在任何环境下:
1176
-
1177
- configure do
1178
- # setting one option
1179
- set :option, 'value'
1180
-
1181
- # setting multiple options
1182
- set :a => 1, :b => 2
1183
-
1184
- # same as `set :option, true`
1185
- enable :option
1186
-
1187
- # same as `set :option, false`
1188
- disable :option
1189
-
1190
- # you can also have dynamic settings with blocks
1191
- set(:css_dir) { File.join(views, 'css') }
1192
- end
1193
-
1194
- 只当环境 (RACK_ENV environment 变量) 被设定为
1195
- <tt>:production</tt>的时候运行:
1196
-
1197
- configure :production do
1198
- ...
1199
- end
1200
-
1201
- 当环境被设定为 <tt>:production</tt> 或者
1202
- <tt>:test</tt>的时候运行:
1203
-
1204
- configure :production, :test do
1205
- ...
1206
- end
1207
-
1208
- 你可以使用 <tt>settings</tt> 获得这些配置:
1209
-
1210
- configure do
1211
- set :foo, 'bar'
1212
- end
1213
-
1214
- get '/' do
1215
- settings.foo? # => true
1216
- settings.foo # => 'bar'
1217
- ...
1218
- end
1219
-
1220
- === 可选的设置
1221
-
1222
- [absolute_redirects] 如果被禁用,Sinatra会允许使用相对路径重定向,
1223
- 但是,Sinatra就不再遵守 RFC 2616标准
1224
- (HTTP 1.1), 该标准只允许绝对路径重定向。
1225
-
1226
- 如果你的应用运行在一个未恰当设置的反向代理之后,
1227
- 你需要启用这个选项。注意 +url+ 辅助方法
1228
- 仍然会生成绝对 URL,除非你传入
1229
- +false+ 作为第二参数。
1230
-
1231
- 默认禁用。
1232
-
1233
- [add_charsets] 设定 <tt>content_type</tt> 辅助方法会
1234
- 自动加上字符集信息的多媒体类型。
1235
-
1236
- 你应该添加而不是覆盖这个选项:
1237
-
1238
- settings.add_charsets << "application/foobar"
1239
-
1240
- [app_file] 主应用文件,用来检测项目的根路径,
1241
- views和public文件夹和内联模板。
1242
-
1243
- [bind] 绑定的IP 地址 (默认: 0.0.0.0)。
1244
- 仅对于内置的服务器有用。
1245
-
1246
- [default_encoding] 默认编码
1247
- (默认为 <tt>"utf-8"</tt>)。
1248
-
1249
- [dump_errors] 在log中显示错误。
1250
-
1251
- [environment] 当前环境,默认是 <tt>ENV['RACK_ENV']</tt>,
1252
- 或者 <tt>"development"</tt> 如果不可用。
1253
-
1254
- [logging] 使用logger
1255
-
1256
- [lock] 对每一个请求放置一个锁,
1257
- 只使用进程并发处理请求。
1258
-
1259
- 如果你的应用不是线程安全则需启动。
1260
- 默认禁用。
1261
-
1262
- [method_override] 使用 <tt>_method</tt> 魔法以允许在旧的浏览器中在
1263
- 表单中使用 put/delete 方法
1264
-
1265
- [port] 监听的端口号。只对内置服务器有用。
1266
-
1267
- [prefixed_redirects] 是否添加 <tt>request.script_name</tt> 到
1268
- 重定向请求,如果没有设定绝对路径。那样的话
1269
- <tt>redirect '/foo'</tt> 会和
1270
- <tt>redirect to('/foo')</tt>起相同作用。默认禁用。
1271
-
1272
- [public_folder] public文件夹的位置。
1273
-
1274
- [reload_templates] 是否每个请求都重新载入模板。
1275
- 在development mode和 Ruby 1.8.6 中被企业(用来
1276
- 消除一个Ruby内存泄漏的bug)。
1277
-
1278
- [root] 项目的根目录。
1279
-
1280
- [raise_errors] 抛出异常(应用会停下)。
1281
-
1282
- [run] 如果启用,Sinatra会开启web服务器。
1283
- 如果使用rackup或其他方式则不要启用。
1284
-
1285
- [running] 内置的服务器在运行吗?
1286
- 不要修改这个设置!
1287
-
1288
- [server] 服务器,或用于内置服务器的列表。
1289
- 默认是 ['thin', 'mongrel', 'webrick'], 顺序表明了
1290
- 优先级。
1291
-
1292
- [sessions] 开启基于cookie的sesson。
1293
-
1294
- [show_exceptions] 在浏览器中显示一个stack trace。
1295
-
1296
- [static] Sinatra是否处理静态文件。
1297
- 当服务器能够处理则禁用。
1298
- 禁用会增强性能。
1299
- 默认开启。
1300
-
1301
- [views] views 文件夹。
1302
-
1303
- == 错误处理
1304
-
1305
- 错误处理在与路由和前置过滤器相同的上下文中运行,
1306
- 这意味着你可以使用许多好东西,比如 <tt>haml</tt>, <tt>erb</tt>,
1307
- <tt>halt</tt>,等等。
1308
-
1309
- === 未找到
1310
-
1311
- 当一个 <tt>Sinatra::NotFound</tt> 错误被抛出的时候,
1312
- 或者响应状态码是404,<tt>not_found</tt> 处理器会被调用:
1313
-
1314
- not_found do
1315
- 'This is nowhere to be found'
1316
- end
1317
-
1318
- === 错误
1319
-
1320
- +error+ 处理器,在任何路由代码块或者过滤器抛出异常的时候会被调用。
1321
- 异常对象可以通过<tt>sinatra.error</tt> Rack 变量获得:
1322
-
1323
-
1324
- error do
1325
- 'Sorry there was a nasty error - ' + env['sinatra.error'].name
1326
- end
1327
-
1328
- 自定义错误:
1329
-
1330
- error MyCustomError do
1331
- 'So what happened was...' + env['sinatra.error'].message
1332
- end
1333
-
1334
- 那么,当这个发生的时候:
1335
-
1336
- get '/' do
1337
- raise MyCustomError, 'something bad'
1338
- end
1339
-
1340
- 你会得到:
1341
-
1342
- So what happened was... something bad
1343
-
1344
- 另一种替代方法是,为一个状态码安装错误处理器:
1345
-
1346
- error 403 do
1347
- 'Access forbidden'
1348
- end
1349
-
1350
- get '/secret' do
1351
- 403
1352
- end
1353
-
1354
- 或者一个范围:
1355
-
1356
- error 400..510 do
1357
- 'Boom'
1358
- end
1359
-
1360
- 在运行在development环境下时,Sinatra会安装特殊的
1361
- <tt>not_found</tt> 和 <tt>error</tt> 处理器。
1362
-
1363
- == Rack 中间件
1364
-
1365
- Sinatra 依靠 Rack[http://rack.rubyforge.org/],
1366
- 一个面向Ruby web框架的最小标准接口。
1367
- Rack的一个最有趣的面向应用开发者的能力是支持“中间件”——坐落在服务器和你的应用之间,
1368
- 监视 并/或 操作HTTP请求/响应以
1369
- 提供多样类型的常用功能。
1370
-
1371
- Sinatra 让建立Rack中间件管道异常简单,
1372
- 通过顶层的 +use+ 方法:
1373
-
1374
- require 'sinatra'
1375
- require 'my_custom_middleware'
1376
-
1377
- use Rack::Lint
1378
- use MyCustomMiddleware
1379
-
1380
- get '/hello' do
1381
- 'Hello World'
1382
- end
1383
-
1384
- +use+ 的语义和在 Rack::Builder[http://rack.rubyforge.org/doc/classes/Rack/Builder.html]
1385
- DSL(在rack文件中最频繁使用)中定义的完全一样。例如,+use+
1386
- 方法接受 多个/可变 参数,包括代码块:
1387
-
1388
- use Rack::Auth::Basic do |username, password|
1389
- username == 'admin' && password == 'secret'
1390
- end
1391
-
1392
- Rack中分布有多样的标准中间件,针对日志,
1393
- 调试,URL路由,认证和session处理。
1394
- Sinatra会自动使用这里面的大部分组件,
1395
- 所以你一般不需要显示地 +use+ 他们。
1396
-
1397
- == 测试
1398
-
1399
- Sinatra的测试可以使用任何基于Rack的测试程序库或者框架来编写。
1400
- {Rack::Test}[http://gitrdoc.com/brynary/rack-test]
1401
- 是推荐候选:
1402
-
1403
- require 'my_sinatra_app'
1404
- require 'test/unit'
1405
- require 'rack/test'
1406
-
1407
- class MyAppTest < Test::Unit::TestCase
1408
- include Rack::Test::Methods
1409
-
1410
- def app
1411
- Sinatra::Application
1412
- end
1413
-
1414
- def test_my_default
1415
- get '/'
1416
- assert_equal 'Hello World!', last_response.body
1417
- end
1418
-
1419
- def test_with_params
1420
- get '/meet', :name => 'Frank'
1421
- assert_equal 'Hello Frank!', last_response.body
1422
- end
1423
-
1424
- def test_with_rack_env
1425
- get '/', {}, 'HTTP_USER_AGENT' => 'Songbird'
1426
- assert_equal "You're using Songbird!", last_response.body
1427
- end
1428
- end
1429
-
1430
- 请注意: 内置的 Sinatra::Test 模块和 Sinatra::TestHarness 类
1431
- 在 0.9.2 版本已废弃。
1432
-
1433
- == Sinatra::Base - 中间件,程序库和模块化应用
1434
-
1435
- 把你的应用定义在顶层,对于微型应用这会工作得很好,
1436
- 但是在构建可复用的组件时候会带来客观的不利,
1437
- 比如构建Rack中间件,Rails metal,带有服务器组件的简单程序库,
1438
- 或者甚至是Sinatra扩展。顶层的DSL污染了Object命名空间,
1439
- 并假定了一个微型应用风格的配置 (例如, 单一的应用文件,
1440
- ./public 和 ./views 目录,日志,异常细节页面,等等)。
1441
- 这时应该让 Sinatra::Base 走到台前了:
1442
-
1443
- require 'sinatra/base'
1444
-
1445
- class MyApp < Sinatra::Base
1446
- set :sessions, true
1447
- set :foo, 'bar'
1448
-
1449
- get '/' do
1450
- 'Hello world!'
1451
- end
1452
- end
1453
-
1454
- Sinatra::Base子类可用的方法实际上就是通过顶层 DSL
1455
- 可用的方法。
1456
- 大部分顶层应用可以通过两个改变转换成Sinatra::Base组件:
1457
-
1458
- * 你的文件应当引入 +sinatra/base+ 而不是 +sinatra+;
1459
- 否则,所有的Sinatra的 DSL 方法将会被引进到
1460
- 主命名空间。
1461
- * 把你的应用的路由,错误处理,过滤器和选项放在
1462
- 一个Sinatra::Base的子类中。
1463
-
1464
- <tt>+Sinatra::Base+</tt> 是一张白纸。大部分的选项默认是禁用的,
1465
- 包含内置的服务器。参见 {选项和配置}[http://sinatra.github.com/configuration.html]
1466
- 查看可用选项的具体细节和他们的行为。
1467
-
1468
- === 模块化 vs. 传统的方式
1469
-
1470
- 与通常的认识相反,传统的方式没有任何错误。
1471
- 如果它适合你的应用,你不需要转换到模块化的应用。
1472
-
1473
- 和模块化方式相比只有两个缺点:
1474
-
1475
- * 你对每个Ruby进程只能定义一个Sinatra应用,如果你需要更多,
1476
- 切换到模块化方式。
1477
-
1478
- * 传统方式使用代理方法污染了 Object 。如果你打算
1479
- 把你的应用封装进一个 library/gem,转换到模块化方式。
1480
-
1481
- 没有任何原因阻止你混合模块化和传统方式。
1482
-
1483
- 如果从一种转换到另一种,你需要注意settings中的
1484
- 一些微小的不同:
1485
-
1486
- Setting Classic Modular
1487
-
1488
- app_file file loading sinatra nil
1489
- run $0 == app_file false
1490
- logging true false
1491
- method_override true false
1492
- inline_templates true false
1493
-
1494
-
1495
- === 运行一个模块化应用
1496
-
1497
- 有两种方式运行一个模块化应用,使用
1498
- <tt>run!</tt>来运行:
1499
-
1500
- # my_app.rb
1501
- require 'sinatra/base'
1502
-
1503
- class MyApp < Sinatra::Base
1504
- # ... app code here ...
1505
-
1506
- # start the server if ruby file executed directly
1507
- run! if app_file == $0
1508
- end
1509
-
1510
- 运行:
1511
-
1512
- ruby my_app.rb
1513
-
1514
- 或者使用一个 <tt>config.ru</tt>,允许你使用任何Rack处理器:
1515
-
1516
- # config.ru
1517
- require './my_app'
1518
- run MyApp
1519
-
1520
- 运行:
1521
-
1522
- rackup -p 4567
1523
-
1524
- === 使用config.ru运行传统方式的应用
1525
-
1526
- 编写你的应用:
1527
-
1528
- # app.rb
1529
- require 'sinatra'
1530
-
1531
- get '/' do
1532
- 'Hello world!'
1533
- end
1534
-
1535
- 加入相应的 <tt>config.ru</tt>:
1536
-
1537
- require './app'
1538
- run Sinatra::Application
1539
-
1540
- === 什么时候用 config.ru?
1541
-
1542
- 以下情况你可能需要使用 <tt>config.ru</tt>:
1543
-
1544
- * 你要使用不同的 Rack 处理器部署 (Passenger, Unicorn,
1545
- Heroku, ...).
1546
- * 你想使用一个或者多个 <tt>Sinatra::Base</tt>的子类.
1547
- * 你只想把Sinatra当作中间件使用,而不是端点。
1548
-
1549
- <b>你并不需要切换到<tt>config.ru</tt>仅仅因为你切换到模块化方式,
1550
- 你同样不需要切换到模块化方式,
1551
- 仅仅因为要运行 <tt>config.ru</tt>.</b>
1552
-
1553
- === 把Sinatra当成中间件来使用
1554
-
1555
- 不仅Sinatra有能力使用其他的Rack中间件,任何Sinatra
1556
- 应用程序都可以反过来自身被当作中间件,被加在任何Rack端点前面。
1557
- 这个端点可以是任何Sinatra应用,或者任何基于Rack的应用程序
1558
- (Rails/Ramaze/Camping/...)。
1559
-
1560
- require 'sinatra/base'
1561
-
1562
- class LoginScreen < Sinatra::Base
1563
- enable :sessions
1564
-
1565
- get('/login') { haml :login }
1566
-
1567
- post('/login') do
1568
- if params[:name] = 'admin' and params[:password] = 'admin'
1569
- session['user_name'] = params[:name]
1570
- else
1571
- redirect '/login'
1572
- end
1573
- end
1574
- end
1575
-
1576
- class MyApp < Sinatra::Base
1577
- # 在前置过滤器前运行中间件
1578
- use LoginScreen
1579
-
1580
- before do
1581
- unless session['user_name']
1582
- halt "Access denied, please <a href='/login'>login</a>."
1583
- end
1584
- end
1585
-
1586
- get('/') { "Hello #{session['user_name']}." }
1587
- end
1588
-
1589
- == 变量域和绑定
1590
-
1591
- 当前所在的变量域决定了哪些方法和变量是可用的。
1592
-
1593
-
1594
- === 应用/类 变量域
1595
-
1596
- 每个Sinatra应用相当与Sinatra::Base的一个子类。
1597
- 如果你在使用顶层DSL(<tt>require 'sinatra'</tt>),那么这个类就是
1598
- Sinatra::Application,或者这个类就是你显式创建的子类。
1599
- 在类层面,你具有的方法类似于 `get` 或者 `before`,但是你不能访问
1600
- `request` 对象或者 `session`, 因为对于所有的请求,
1601
- 只有单一的应用类。
1602
-
1603
- 通过 `set` 创建的选项是类层面的方法:
1604
-
1605
- class MyApp < Sinatra::Base
1606
- # 嘿,我在应用变量域!
1607
- set :foo, 42
1608
- foo # => 42
1609
-
1610
- get '/foo' do
1611
- # 嘿,我不再处于应用变量域了!
1612
- end
1613
- end
1614
-
1615
- 在下列情况下你将拥有应用变量域的绑定:
1616
-
1617
- * 在应用类中
1618
- * 在扩展中定义的方法
1619
- * 传递给 `helpers` 的代码块
1620
- * 用作`set`值的过程/代码块
1621
-
1622
- 你可以访问变量域对象(就是应用类)就像这样:
1623
-
1624
- * 通过传递给代码块的对象 (<tt>configure { |c| ... }</tt>)
1625
- * 在请求变量域中使用`settings`
1626
-
1627
- === 请求/实例 变量域
1628
-
1629
- 对于每个进入的请求,一个新的应用类的实例会被创建
1630
- 所有的处理器代码块在该变量域被运行。在这个变量域中,
1631
- 你可以访问 `request` 和 `session` 对象,或者调用渲染方法比如
1632
- `erb` 或者 `haml`。你可以在请求变量域当中通过`settings`辅助方法
1633
- 访问应用变量域:
1634
-
1635
- class MyApp < Sinatra::Base
1636
- # 嘿,我在应用变量域!
1637
- get '/define_route/:name' do
1638
- # 针对 '/define_route/:name' 的请求变量域
1639
- @value = 42
1640
-
1641
- settings.get("/#{params[:name]}") do
1642
- # 针对 "/#{params[:name]}" 的请求变量域
1643
- @value # => nil (并不是相同的请求)
1644
- end
1645
-
1646
- "Route defined!"
1647
- end
1648
- end
1649
-
1650
- 在以下情况将获得请求变量域:
1651
-
1652
- * get/head/post/put/delete 代码块
1653
- * 前置/后置 过滤器
1654
- * 辅助方法
1655
- * 模板/视图
1656
-
1657
- === 代理变量域
1658
-
1659
- 代理变量域只是把方法转送到类变量域。可是,
1660
- 他并非表现得100%类似于类变量域, 因为你并不能获得类的绑定:
1661
- 只有显式地标记为供代理使用的方法才是可用的,
1662
- 而且你不能和类变量域共享变量/状态。(解释:你有了一个不同的
1663
- `self`)。 你可以显式地增加方法代理,通过调用
1664
- <tt>Sinatra::Delegator.delegate :method_name</tt>。
1665
-
1666
- 在以下情况将获得代理变量域:
1667
-
1668
- * 顶层的绑定,如果你做过 <tt>require "sinatra"</tt>
1669
- * 在扩展了 `Sinatra::Delegator` mixin的对象
1670
-
1671
- 自己在这里看一下代码:
1672
- {Sinatra::Delegator mixin}[http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/base.rb#L1128]
1673
- 已经 {被包含进了主命名空间}[http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/main.rb#L28]。
1674
-
1675
- == 命令行
1676
-
1677
- Sinatra 应用可以被直接运行:
1678
-
1679
- ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER]
1680
-
1681
- 选项是:
1682
-
1683
- -h # help
1684
- -p # 设定端口 (默认是 4567)
1685
- -o # 设定主机名 (默认是 0.0.0.0)
1686
- -e # 设定环境 (默认是 development)
1687
- -s # 限定 rack 服务器/处理器 (默认是 thin)
1688
- -x # 打开互斥锁 (默认是 off)
1689
-
1690
- == 必要条件
1691
-
1692
- 推荐在 Ruby 1.8.7, 1.9.2, JRuby 或者 Rubinius 上安装Sinatra。
1693
-
1694
- 下面的Ruby版本是官方支持的:
1695
-
1696
- [ Ruby 1.8.6 ]
1697
- 不推荐在1.8.6上安装Sinatra,
1698
- 但是直到Sinatra 1.3.0发布才会放弃对它的支持。
1699
- RDoc 和 CoffeScript模板不被这个Ruby版本支持。
1700
- 1.8.6在它的Hash实现中包含一个内存泄漏问题,
1701
- 该问题会被1.1.1版本之前的Sinatra引发。
1702
- 当前版本使用性能下降的代价排除了这个问题。你需要把Rack降级到1.1.x,
1703
- 因为Rack >= 1.2不再支持1.8.6。
1704
-
1705
- [ Ruby 1.8.7 ]
1706
- 1.8.7 被完全支持,但是,如果没有特别原因,
1707
- 我们推荐你升级到 1.9.2 或者切换到 JRuby 或者 Rubinius.
1708
-
1709
- [ Ruby 1.9.2 ]
1710
- 1.9.2 被支持而且推荐。注意 Radius 和 Markaby
1711
- 模板并不和1.9兼容。不要使用 1.9.2p0, 它被已知会产生
1712
- segmentation faults.
1713
-
1714
- [ Rubinius ]
1715
- Rubinius 被官方支持 (Rubinius >= 1.2.2),
1716
- 除了Textile模板。
1717
-
1718
- [ JRuby ]
1719
- JRuby 被官方支持 (JRuby >= 1.5.6)。
1720
- 目前未知和第三方模板库有关的问题,
1721
- 但是,如果你选择了JRuby,请查看一下JRuby rack 处理器,
1722
- 因为 Thin web 服务器还没有在JRuby上获得支持。
1723
-
1724
- 我们也会时刻关注新的Ruby版本。
1725
-
1726
- 下面的 Ruby 实现没有被官方支持,
1727
- 但是已知可以运行 Sinatra:
1728
-
1729
- * JRuby 和 Rubinius 老版本
1730
- * MacRuby
1731
- * Maglev
1732
- * IronRuby
1733
- * Ruby 1.9.0 and 1.9.1
1734
-
1735
- 不被官方支持的意思是,如果在不被支持的平台上有运行错误,
1736
- 我们假定不是我们的问题,而是平台的问题。
1737
-
1738
- Sinatra应该会运行在任何支持上述Ruby实现的操作系统。
1739
-
1740
-
1741
- == 紧追前沿
1742
-
1743
- 如果你喜欢使用 Sinatra 的最新鲜的代码,请放心的使用 master
1744
- 分支来运行你的程序,它会非常的稳定。
1745
- cd myapp
1746
- git clone git://github.com/sinatra/sinatra.git
1747
- ruby -Isinatra/lib myapp.rb
1748
-
1749
- 我们也会不定期的发布预发布gems,所以你也可以运行
1750
-
1751
- gem install sinatra --pre
1752
-
1753
- 来获得最新的特性。
1754
-
1755
- === 通过Bundler
1756
- 如果你想使用最新的Sinatra运行你的应用,通过
1757
- {Bundler}[http://gembundler.com/] 是推荐的方式。
1758
-
1759
- 首先,安装bundler,如果你还没有安装:
1760
-
1761
- gem install bundler
1762
-
1763
- 然后,在你的项目目录下,创建一个 +Gemfile+:
1764
-
1765
- source :rubygems
1766
- gem 'sinatra', :git => "git://github.com/sinatra/sinatra.git"
1767
-
1768
- # 其他的依赖关系
1769
- gem 'haml' # 举例,如果你想用haml
1770
- gem 'activerecord', '~> 3.0' # 也许你还需要 ActiveRecord 3.x
1771
-
1772
- 请注意在这里你需要列出你的应用的所有依赖关系。
1773
- Sinatra的直接依赖关系 (Rack and Tilt) 将会,
1774
- 自动被Bundler获取和添加。
1775
-
1776
- 现在你可以像这样运行你的应用:
1777
-
1778
- bundle exec ruby myapp.rb
1779
-
1780
- === 使用自己的
1781
- 创建一个本地克隆并通过 <tt>sinatra/lib</tt> 目录运行你的应用,
1782
- 通过 <tt>$LOAD_PATH</tt>:
1783
-
1784
- cd myapp
1785
- git clone git://github.com/sinatra/sinatra.git
1786
- ruby -Isinatra/lib myapp.rb
1787
-
1788
- 为了在未来更新 Sinatra 源代码:
1789
-
1790
- cd myapp/sinatra
1791
- git pull
1792
-
1793
- === 全局安装
1794
-
1795
- 你可以自行编译 gem :
1796
-
1797
-
1798
- git clone git://github.com/sinatra/sinatra.git
1799
- cd sinatra
1800
- rake sinatra.gemspec
1801
- rake install
1802
-
1803
- 如果你以root身份安装 gems,最后一步应该是
1804
-
1805
- sudo rake install
1806
-
1807
- == 更多
1808
-
1809
- * {项目主页(英文)}[http://www.sinatrarb.com/] - 更多的文档,
1810
- 新闻,和其他资源的链接。
1811
- * {贡献}[http://www.sinatrarb.com/contributing] - 找到了一个bug?
1812
- 需要帮助?有了一个 patch?
1813
- * {问题追踪}[http://github.com/sinatra/sinatra/issues]
1814
- * {Twitter}[http://twitter.com/sinatra]
1815
- * {邮件列表}[http://groups.google.com/group/sinatrarb/topics]
1816
- * {IRC: #sinatra}[irc://chat.freenode.net/#sinatra] on http://freenode.net