【问题标题】:Use ActionView helper blocks in a rails presenter在 Rails Presenter 中使用 ActionView 辅助块
【发布时间】:2013-12-06 10:08:21
【问题描述】:

我正在尝试将一些逻辑从我的观点中移出,并且我正在使用演示者来做到这一点。受影响的代码如下。

演讲者:

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

视图部分:

(这里的profile是一个presenter对象)

<%= 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>

如何防止方块在第一次触发?

【问题讨论】:

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


    【解决方案1】:

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

    link_to &block, path
    

    但是,即使这可以修复,我认为这是对 Presenter 的滥用。如果“一些东西”是为了视图的逻辑,把它放在视图中。如果是关于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中做一个父链接方法,并在子类中继承。

    【讨论】:

    • 我对演示者很陌生,所以我很可能会误用它,但这里的目标是让演示者基本上决定配置文件应该由锚点还是 div 表示。当我切换到link_to path, &amp;block 时,同样的问题存在。我一直在重构,这需要改进,但我很好奇它为什么会这样(打印两次)
    • 那是因为capture,它会追加输出。对于演示者,您还可以查看 Draper gem,它提供了更多功能且易于使用。
    • 我无法让这个功能在 Presenter 中工作,但我确实加倍返回并将逻辑移至帮助程序。我尝试对此进行移动捕获,但它并没有改变双重渲染的问题。我还在研究这个,但我没有运气
    猜你喜欢
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    相关资源
    最近更新 更多