【问题标题】:Is template variable getting initialized from self in application_helper.rb in this presenter?模板变量是否在此演示者的 application_helper.rb 中从 self 初始化?
【发布时间】: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的原因。

标签: ruby-on-rails presenter


【解决方案1】:

没错,就是当前视图对象本身。

我写了一篇关于 PORO 演示者的博文,应该会有所帮助

http://joewoodward.me/i-take-it-back/

【讨论】:

  • 发布链接不应被视为答案。您应该添加链接作为问题的评论或提供关于 SO 本身的答案,如果需要,可以指向您的博客。
猜你喜欢
  • 2020-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多