通常这类事情是通过辅助方法处理的,例如:
def profile_link(profile)
profile.link ? content_tag(:a, h(profile.name), :href => profile.link) : 'No profile'
end
不幸的是,您无法在查看时扩展模型的 Presenter 风格的帮助器方法中分层。它们需要以一种带有参数的过程方式来调用,这是一种反面向对象的方式。
Rails MVC 领域不完全支持 Presenter 方法,因为它需要绑定到视图才能访问正确呈现内容所需的各种帮助器方法,以及有关可能影响演示的会话的信息。
更可靠的方法可能是执行以下操作:
class ProfilePresenter
def initialize(view, profile)
@profile = profile
@view = view
yield(self) if (block_given?)
end
def link
@profile.link ? @view.content_tag(:a, @view.h(profile.name), :href => @profile.link) : 'No profile'
end
def method_missing(*args)
@profile.send(*args)
end
end
在您看来,这将显示为:
<% ProfilePresenter.new(self, @profile) do |profile| %>
<div><%= profile.link %>
<% end %>
您可以通过创建一个辅助方法来简化调用它,该方法会执行一些有点疯狂的操作,例如:
def presenter_for(model)
"#{model.class}Presenter".constantize.new(self, model) do |presenter|
yield(presenter) if (block_given?)
end
end
这意味着您的调用要简单得多:
<% presenter_for(@profile) do |profile| %>
<div><%= profile.link %>
<% end %>