一個容器,用於儲存特定動作發送給不同 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 255 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 262 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 280 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 271 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 297 def negotiate_format(request) @format = request.negotiate_mime(@responses.keys) end
response() 連結
來源: 顯示 |
# File actionpack/lib/action_controller/metal/mime_responds.rb, line 284
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