您在操作中调用的render 方法在ActionController::Base 中定义。
def render(action = nil, options = {}, &blk)
options = _normalize_options(action, options, &blk)
super(options)
end
此方法将调用传递给super,后者调用ActionController::Rendering 中定义的render 方法。
def render(options)
super
self.content_type ||= options[:_template].mime_type.to_s
response_body
end
ActionController::Rendering 实际上是一个模块,混合到 base.rb 文件开头的 ActionController::Base 类中。
include ActionController::Redirecting
include ActionController::Rendering # <--
include ActionController::Renderers::All
反过来,ActionController::Rendering 包括 AbstractController::Rendering,正如您在 ActionController::Rendering 模块定义中看到的那样。
module ActionController
module Rendering
extend ActiveSupport::Concern
included do
include AbstractController::Rendering
include AbstractController::LocalizedCache
end
AbstractController::Rendering 提供了一个render 方法,它是渲染链中调用的最后一个方法。
# Mostly abstracts the fact that calling render twice is a DoubleRenderError.
# Delegates render_to_body and sticks the result in self.response_body.
def render(*args)
if response_body
raise AbstractController::DoubleRenderError, "Can only render or redirect once per action"
end
self.response_body = render_to_body(*args)
end
完整的链条是
AbstractController::Base#render
--> super()
--> ActionController::Rendering#render
--> super()
--> AbstractController::Rendering#render
--> render_to_body