大家都知道使用 respond_to 的好处。respond_to 将访问中的mime类型成功的囊括到其小而精致的结构里,而且访问里的mime类型在很多其他地方的应用比查询语句更加有效。比如,在根据不同访问的类型 选择应用不同的过滤行为总是有好处的。今天起您将可以通过新的 request.format.html?,request.format.xml? 等语句方便得完成任务。
class MyController < ApplicationController
# 针对访问类型切换登录授权方法
before_filter do |c|
c.use_session_auth if c.request.format.html?
c.use_token_auth if c.request.format.xml?
end
end
或者您也可以使用简洁的方法来关闭sessions (来自变更列表的示例):
class MyController < ApplicationController
# 为所有非html访问关闭session功能
sessions :off, :if => Proc.new { |request| not request.format.html? }
end
总结的说,那些令人讨厌又不得不需要鉴定的 mime类型 终于可以被完好的解决。这些代码不但可以识别”市面“上认可的 mime类型,它们还可以用来识别您为自己注册的 mime类型。
# 因为我想大家都同意我值得拥有自己的mime-type
Mime::Type.register "text/ryan", :ryan
class MyController < ApplicationController
# 为所有ryan的访问关闭session功能
sessions :off, :if => Proc.new { |request| request.format.ryan? }
end
感谢 Yudi 提供本系列文档
原文作者是 Ryan Daigle, 请访问他的博客