【发布时间】:2016-08-23 14:42:29
【问题描述】:
所以我在 Rails 4.2 应用程序中看到了一些代码,如下所示。
1) kite_presenter.rb 中的@template 是什么类型的对象?它是 ActionView 的一个实例吗?这就是它如何访问诸如 image_tag 之类的助手的方式? 2)如果1的答案是Actionview的一个实例,在application_helper.rb中,self怎么知道引用一个ActionView对象?
kite_presenter.rb
class KitePresenter < SimpleDelegator
def initialize(kite, template)
super(kite)
@template = template
end
def tail_display
h.image_tag("tail.png", class: 'gray')
end
end
application_helper.rb
module ApplicationHelper
def present(object, klass = nil)
klass ||= "#{object.class}Presenter".constantize
presenter = klass.new(object, self)
yield presenter if block_given?
presenter
end
end
some_html.erb
<% present(kite) do |kite_presenter| %>
<%= kite_presenter.tail_display %>
<% end %>
【问题讨论】:
-
joe woodward 说的没错,确实是
ActionView的一个实例。我在 rails 源代码中找不到演示这一点的代码部分,但是对于您的第二个问题,该模块与视图混合在一起。准确的说,它是一个include,它将模块中的方法添加到实例中,这就是self指向ActionView的原因。