跳至内容 跳至搜索
方法
U

实例公共方法

use_renderer(*args)

别名: use_renderers

use_renderers(*args)

通过名称,将渲染器或渲染器添加到控制器操作中可用的 _renderers 中。

这在使用 ActionController::Metal 控制器进行渲染时很有用,或者以其他方式为特定控制器添加可用的渲染器过程。

ActionController::BaseActionController::API 都包含 ActionController::Renderers::All,使得所有渲染器都可以在控制器中使用。请参阅 Renderers::RENDERERS 和 Renderers.add

由于 ActionController::Metal 控制器无法渲染,因此控制器必须包含 AbstractController::RenderingActionController::RenderingActionController::Renderers,并且至少有一个渲染器。

与其包含 ActionController::Renderers::All 并包含所有渲染器,不如通过将渲染器名称或名称传递给 use_renderers 来指定要包含的渲染器。例如,一个仅包含 :json 渲染器(_render_with_renderer_json)的控制器可能如下所示:

class MetalRenderingController < ActionController::Metal
  include AbstractController::Rendering
  include ActionController::Rendering
  include ActionController::Renderers

  use_renderers :json

  def show
    render json: record
  end
end

您必须指定一个 use_renderer,否则 controller.renderercontroller._renderers 将为 nil,并且操作将失败。

也别名为: use_renderer
# File actionpack/lib/action_controller/metal/renderers.rb, line 142
def use_renderers(*args)
  renderers = _renderers + args
  self._renderers = renderers.freeze
end