谁能解释一下 render() 是从哪里来的 ActionController::Base?
我设法追查到了这么远:
ActionController::Base 包括 ActionController::Rendering 模块,其中 定义了 render() 方法。然而,这个定义调用了 render() 的 父类(super class)。父类(super class)是 ActionController::Metal。其中在其 turn 继承自 AbstractController::Base。这些都没有渲染 () 定义或包含。
现在,大概它来自 AbstractController::Rendering,但我是 真的很想念它是如何被包含在内的。
最佳答案
您在 Action 中调用的 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
方法,它是渲染链中调用的 final方法。
# 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
关于ruby-on-rails - rails 3.0: ActionController::Base render(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2094678/