跳至内容 跳至搜索

一个容器,用于存放当前控制器针对特定操作响应不同 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
包含的模块

Attributes

[RW] 格式

类公共方法

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

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