何时在模型中定义方法的属性?

时间:2018-09-25 12:18:26

标签: ruby-on-rails

我正在写一个演讲者。我想委托Model的属性方法。我写了下面的代码。

app / presenters / model_presenter.rb

class ModelPresenter
  include HTMLBuilder

  attr_reader :object, :view_context
  delegated_methods  = ActionView::Base.instance_methods(true)
  delegated_methods -= Object.instance_methods(true)
  delegate *delegated_methods, to: :view_context

  def initialize(object, view_context)
    @object       = object
    @view_context = view_context
  end

app / presenters / staff_member_presenter.rb

class StaffMemberPresenter < ModelPresenter
  delegated_methods  = StaffMember.instance_methods(true)
  delegated_methods -= ActiveRecord::Base.instance_methods(true)
  delegate *delegated_methods, to: :object

我认为 ActiveRecord.instance_methods 包含诸如电子邮件,名字,姓氏,暂停等属性方法。但不包括在内。运行 StaffMember.new.email 后,它是否包括已暂停和已暂停?等等。我认为这是因为ActiveRecord动态地定义属性方法(例如email,first_name)。所以我用下面的代码解决了这个问题。

app / presenter / staff_member_presenter.rb

class StaffMemberPresenter < ModelPresenter
  StaffMember.new.created_at
  delegated_methods  = StaffMember.instance_methods(true)
  delegated_methods -= ActiveRecord::Base.instance_methods(true
  delegate *delegated_methods, to: :object

我认为比上述方法更简单。如果您知道简单的方法,您能告诉我吗?

0 个答案:

没有答案