gpt4 book ai didi

ruby-on-rails - 关于 rails 中的演示者模式。有更好的方法吗?

转载 作者:行者123 更新时间:2023-12-04 16:37:22 25 4
gpt4 key购买 nike

我的模型中有:

def presenter
@presenter ||= ProfilePresenter.new(self)
@presenter
end

ProfilePresenter 是一个类,它具有 get_link()、get_img_url(size)、get_sex()、get_relationship_status() 和其他与模型无关的方法,甚至与 Controller 无关,但在看法。

所以现在我通过这样做来使用它们:
Profile.presenter.get_link
# or
Profile.presenter.get_img_url('thumb') # returns the path of the image. is not used to make a db query

真诚地,我认为我错过了演示者的真正概念..但这就是我试图存档的内容,怎么能称之为?

最佳答案

通常这种事情是通过辅助方法处理的,例如:

def profile_link(profile)
profile.link ? content_tag(:a, h(profile.name), :href => profile.link) : 'No profile'
end

不幸的是,您不能在 View 时将扩展模型的 Presenter 样式的辅助方法分层。它们需要以带有参数的程序方式调用,一种反OO。

Rails MVC 领域不完全支持 Presenter 方法,因为它需要绑定(bind)到 View 才能访问正确呈现内容所需的各种帮助方法,以及可能影响演示的 session 信息。

一个更强大的方法可能是做这样的事情:
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

这将在您的 View 中显示为:
<% 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 %>

关于ruby-on-rails - 关于 rails 中的演示者模式。有更好的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2822314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com