Rails:respond_to vs"case"条件

Ale*_*xey 3 ruby-on-rails

respond_to在Rails 中使用而不是case语句有什么好处?我有几个实例变量,我想为某些格式设置相同的方式,但不是HTML.这似乎不起作用:

respond_to do |format|
  format.html do
    # ...
  end
  format.any(:csv, :xml) do
    # common stuff
  end
  format.csv do
    # ...
  end
  format.xml do
    # ...
  end
end
Run Code Online (Sandbox Code Playgroud)

我想我最终会使用一些case request.format而不是完全使用respond_to:

case request.format
when 'html'
  # ...
when 'csv', 'xml'
  # common stuff
end
# more common stuff
case request.format
when 'html'
  # render
when 'csv'
  # custom render csv
when 'xml'
  # render xml with a template
end
Run Code Online (Sandbox Code Playgroud)

所以我想知道什么是好的用例respond_to,哪里case request.format看起来不会更好?

j03*_*03w 8

respond_to这不仅仅是一种了解客户期望的响应类型的方法,而且还是一种告诉rails您愿意提供什么类型的响应的方法.

例如,我们有这个控制器的简单场景:

class SimpleController < ApplicationController
  def index
    respond_to :html, :json
  end
end
Run Code Online (Sandbox Code Playgroud)

客户端发送期望xml响应的请求

curl -H "Accept: application/xml" \
     -H "Content-Type: application/xml" \
     -X GET "host:port/simple/index"
Run Code Online (Sandbox Code Playgroud)

Rails会回应 406

Completed 406 Not Acceptable in 0ms (ActiveRecord: 0.0ms)
Run Code Online (Sandbox Code Playgroud)

但是,如果您只是在示例中request.format使用caselike进行过滤,则客户端将收到500错误,因为rails无法找到请求格式的相应模板.

当然,您也可以respond_to级别上调用,也可以在routes.rb中指定响应格式

潜入rails如果你想获得更深入的解释,这个源代码和API文档.