跳到內容 跳到搜尋

一個容器,用於儲存特定動作發送給不同 MIME 型別要求的目前控制器可以使用的回應。

可以使用區塊來呼叫公用控制器方法 respond_to,此區塊用於定義對不同 MIME 型別的回應,例如 respond_to

respond_to do |format|
  format.html
  format.xml { render xml: @people }
end

在此用法中,傳遞給區塊的參數(上方的 format)是 ActionController::MimeResponds::Collector 類別的一個實例。此物件作為一個容器,可透過在 Collector 上呼叫任何動態產生的 MIME 型別專用方法(例如 htmlxml 等)來儲存可用的回應。每個回應會表示為一個對應的區塊(如果存在)。

後續呼叫 negotiate_format(request) 將會讓 Collector 能夠判斷目前的要求應該回應哪一個特定 MIME 型別,然後可以透過呼叫 response 來存取此回應。

方法
A
C
N
R
包含模組

屬性

[RW] format

類別公用方法

new(mimes, variant = nil)

# 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

實例公用方法

all(*args, &block)

別名為: any

any(*args, &block)

也別名為: all
# 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?()

# 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)

# 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)

# File actionpack/lib/action_controller/metal/mime_responds.rb, line 297
def negotiate_format(request)
  @format = request.negotiate_mime(@responses.keys)
end