在rails presenter中使用ActionView帮助程序块

时间:2013-11-21 18:45:52

标签: ruby-on-rails ruby-on-rails-4 actionview

我正试图从我的观点中移除一些逻辑,而我正在使用演示者这样做。受影响的代码如下。

主讲人:

class ApplicationPresenter < ActionView::Base
  extend Forwardable
  include Rails.application.routes.url_helpers
end

class ProfilesPresenter < ApplicationPresenter
  def_delegators :@profile, :id

  def initialize(profile, user)
    @profile = profile
    @user = user
  end

  def container(&block)
    path = profile_insights_path(id)
    link_to capture(&block), path
  end
end

查看部分:

(此处的配置文件是演示者对象)

<%= content_tag(:li) do %>
  <%= profile.container do %>
    Some Stuff
  <% end %>
<% end %>

我想基本上使用Presenter方法,就像帮助器一样,因此配置文件对其行为方式有“意见”。目前,container方法中没有任何逻辑,但会有。 我唯一的问题是输出显示两次:

<li>
  Some Stuff
  <a href="/profiles/11725854/insights">Some Stuff</a>
</li>

如何防止第一次开火?

1 个答案:

答案 0 :(得分:0)

直接修复虽然未经过验证,但应该从capture删除link_to,例如:

link_to &block, path

然而,即便如此,我认为这是对Presenter的误用。如果“Some Stuff”用于视图的逻辑,则将其置于视图中。如果是关于Profile,为什么不把它直接呈现?主持人的工作就是那些肮脏的事情。

class ProfilesPresenter < ApplicationPresenter
  # ....

  def link_for_some_stuff
    path = profile_insights_path(id)
    link_to "Some Stuff", path
  end
end

# View
li
  = profile.link_to_some_stuff

现在视野渺茫。

如果其他模型需要类似的方法,您可以在ApplicationDecorator中创建父链接方法并在子类中继承它。