当前控制器可用于响应不同 MIME 类型请求的容器,这些请求发送到特定操作。
公共控制器方法 respond_to
可使用一个块调用,该块用于定义对不同 MIME 类型的响应,例如,对于 respond_to
respond_to do |format|
format.html
format.xml { render xml: @people }
end
在此用法中,传递给块的参数(上面的 format
)是 ActionController::MimeResponds::Collector
类的实例。此对象用作容器,其中可用的响应可以通过在 Collector
上调用任何动态生成的 MIME 类型特定方法(例如 html
、xml
等)来存储。如果存在,每个响应都由相应的块表示。
随后调用 negotiate_format(request)
将使 Collector
能够确定它应该为当前请求响应哪个特定的 MIME 类型,然后可以通过调用 response
来访问此响应。
- A
- C
- N
- R
属性
[RW] | format |
类公共方法
new(mimes, variant = nil) 链接
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/mime_responds.rb, line 246 def initialize(mimes, variant = nil) @responses = {} @variant = variant mimes.each { |mime| @responses[Mime[mime]] = nil } end
实例公共方法
any(*args, &block) 链接
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/mime_responds.rb, line 253 def any(*args, &block) if args.any? args.each { |type| send(type, &block) } else custom(Mime::ALL, &block) end end
any_response?() 链接
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/mime_responds.rb, line 271 def any_response? !@responses.fetch(format, false) && @responses[Mime::ALL] end
custom(mime_type, &block) 链接
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/mime_responds.rb, line 262 def custom(mime_type, &block) mime_type = Mime::Type.lookup(mime_type.to_s) unless mime_type.is_a?(Mime::Type) @responses[mime_type] ||= if block_given? block else VariantCollector.new(@variant) end end
negotiate_format(request) 链接
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/mime_responds.rb, line 288 def negotiate_format(request) @format = request.negotiate_mime(@responses.keys) end
response() 链接
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/mime_responds.rb, line 275 def response response = @responses.fetch(format, @responses[Mime::ALL]) if response.is_a?(VariantCollector) # `format.html.phone` - variant inline syntax response.variant elsif response.nil? || response.arity == 0 # `format.html` - just a format, call its block response else # `format.html{ |variant| variant.phone }` - variant block syntax variant_collector = VariantCollector.new(@variant) response.call(variant_collector) # call format block with variants collector variant_collector.variant end end