Chinaunix首页 | 论坛 | 博客
  • 博客访问: 384368
  • 博文数量: 69
  • 博客积分: 1984
  • 博客等级: 上尉
  • 技术积分: 953
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-28 00:43
个人简介

学无所长,一事无成

文章分类

全部博文(69)

文章存档

2015年(19)

2014年(14)

2013年(9)

2012年(17)

2010年(10)

我的朋友

分类: Python/Ruby

2014-04-22 14:59:05

Sinatra 是一个用 ruby 实现的轻量级 web 框架,架构简单,可用于快速实现小规模的程序开发。

常见问题

一、如何让 Sinatra 程序在修改后自动加载

  1. $gem install rerun

  1. $ ruby app.rb
替换成,实践证明: rerun app.rb 即可
  1. $ rerun 'ruby app.rb'
如果使用 rake ,则如下
  1. $ rerun 'rackup'
If you still want in-process reloading, check out .

二、如何使用sessions

sessions 缺省是禁用,需要手工启用:

  1. enable :sessions

  2. get '/foo' do
  3.   session[:message] = 'Hello World!'
  4.   redirect to('/bar')
  5. end

  6. get '/bar' do
  7.   session[:message] # => 'Hello World!'
  8. end
如果你需要为 sessions 设置附加参数,如时间超期,可以使用 


  1. use Rack::Session::Cookie, :key => 'rack.session',
  2.                            :domain => 'foo.com',
  3.                            :path => '/',
  4.                            :expire_after => 2592000, # In seconds
  5.                            :secret => 'change_me'
三、如何获取当前页面的 route
使用 request 对象可以获取相关信息
  1. get '/hello-world' do
  2.   request.path_info # => '/hello-world'
  3.   request.fullpath # => '/hello-world?foo=bar'
  4.   request.url # => ''
  5. end
查看  了解 requrest 对象的更多方法。

四、在 view 中如何使用自定义的 helper


hello.rb
  1. helpers do
  2.   def em(text)
  3.     "#{text}"
  4.   end
  5. end

  6. get '/hello' do
  7.   @subject = 'World'
  8.   haml :hello
  9. end
views/hello.haml:
  1. %p= "Hello " + em(@subject)

五、如何通过多个 url 触发同一个 route/handler
如下:
  1. ["/foo", "/bar", "/baz"].each do |path|
  2.   get path do
  3.     "You've reached me at #{request.path_info}"
  4.   end
  5. end
六、如何将 url 最后一个斜线作为可选项
  1. get '/foo/bar/?' do
  2.   "Hello World"
  3. end
这条路由规则将匹配: "/foo/bar" 和 "/foo/bar/"。感觉跟正则匹配很像哦。

七、如何渲染子目录下的 template

sinatra 不建议你创建复杂的 view 结构,如果你实在要用,可以如下:

  1. get '/' do
  2.   haml :'foo/bar'
  3. end
同以下形式等价

  1. get '/' do
  2.   haml 'foo/bar'.to_sym
  3. end
八、我使用 Thin 服务器,希望能够看到报错信息

添加 --debug 参数
  1. thin --debug --rackup config.ru start

九、如何通过 Sinatra 发送邮件

可以试试   (sudo gem install pony):

  1. require 'pony'
  2. post '/signup' do
  3.   Pony.mail :to => 'you@example.com',
  4.             :from => 'me@example.com',
  5.             :subject => 'Howdy, Partna!'
  6. end
You can even use templates to render the body. In email.erb:

  1. Good day <%= params[:name] %>,

  2. Thanks for signing my guestbook. You're a doll.

  3. Frank
And in mailerapp.rb:

  1. post '/guestbook/sign' do
  2.   Pony.mail :to => params[:email],
  3.             :from => "me@example.com",
  4.             :subject => "Thanks for signing my guestbook, #{params[:name]}!",
  5.             :body => erb(:email)
  6. end
阅读(1432) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~