关于滑轨中的演示者模式.是更好的方法吗? [英] About presenter pattern in rails. is a better way to do it?

查看:57
本文介绍了关于滑轨中的演示者模式.是更好的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中有

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

ProfilePresenter是一个类,该类具有诸如get_link(),get_img_url(size),get_sex(),get_relationship_status()之类的方法以及其他与模型无关的方法,甚至与控制器无关,但被多个使用视图中的时间.

The ProfilePresenter is a class that has methods like, get_link(), get_img_url(size), get_sex(), get_relationship_status() and other methods that have not to do with the model, not even with the controller but is used multiple times in the view.

所以现在我通过以下方式使用它们:

So now i use them by doing this:

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

很抱歉,我认为我错过了演讲者的真正概念.但这就是我想要存档的东西,怎么称呼它呢?

Sincerelly i think i missed out the real concept of presenters.. but this is what m trying to archive, how can be called this?

推荐答案

通常,此类事情是通过辅助方法来处理的,例如:

Normally this sort of thing is handled via helper methods, such as:

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

不幸的是,您无法在演示时扩展用于演示模型的Presenter样式的帮助器方法中.需要以一种过程性的方式使用一种类型的参数来调用它们,例如anti-OO.

It is unfortunate you cannot layer in Presenter-style helper methods that extend a Model at view time. They need to be called in a procedural manner with a parameter, kind of anti-OO.

Rails MVC区域中不完全支持Presenter方法,因为它需要绑定到视图才能访问正确呈现内容所需的各种帮助方法,以及有关可能影响演示的会话信息.

The Presenter approach is not fully supported in the Rails MVC area because it needs to bind to a view in order to have access to the various helper methods required to properly render content, plus information about the session that may impact the presentation.

更健壮的方法可能是执行以下操作:

A more robust approach might be to do something like this:

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

这将在您的视图中显示为:

This would show up in your view as something like:

<% ProfilePresenter.new(self, @profile) do |profile| %>
<div><%= profile.link %>
<% end %>

您可以通过创建一个辅助方法来简化调用过程,该方法可以执行一些疯狂的操作,例如:

You can simplify calling this by making a helper method that does something mildly crazy like:

def presenter_for(model)
  "#{model.class}Presenter".constantize.new(self, model) do |presenter|
    yield(presenter) if (block_given?)
  end
end

这意味着您的通话更加简单:

This means you have a much simpler call:

<% presenter_for(@profile) do |profile| %>
<div><%= profile.link %>
<% end %>

这篇关于关于滑轨中的演示者模式.是更好的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆