如何将共享Rails模型行为移动到mixins?

时间:2013-10-21 18:19:13

标签: ruby rails-activerecord

我有两个几乎相同的模型。我想创建一个或多个mixins,以便我可以分享这些模型之间的行为。这是一个示例模型,其中包括我能想到的每个变体:

class Model < ActiveRecord::Base
  STATUS_OPTIONS = ['new', 'approved', 'rejected', 'deleted']
  attr_accessible :status
  validates_inclusion_of :status, :in => STATUS_OPTIONS

  def self.custom_finder(status)
    find_by_status(status)
  end

  def simple_instance_method
    'easy'
  end
end

我理解从Ruby模块中包含实例方法的一些基础知识,但是当涉及到诸如ActiveRecord类方法,常量等更高级的东西时,我感到很困惑。

module ModelClassMethods
  def custom_finder(status)
    find_by_status(status)
  end
end

module ModelInstanceMethods
  def simple_instance_method
    'easy'
  end
end

class Model < ActiveRecord::Base
  STATUS_OPTIONS = ['new', 'approved', 'rejected', 'deleted']
  attr_accessible :status
  validates_inclusion_of :status, :in => STATUS_OPTIONS

  extend ModelClassMethods
  include ModelInstanceMethods
end

现在如何提取常量和验证方法?

1 个答案:

答案 0 :(得分:0)

常量包含在include中,validates方法族也是实例方法所以......

module ModelInstanceMethods
  STATUS_OPTIONS = ['new', 'approved', 'rejected', 'deleted']

  def simple_instance_method
    'easy'
  end
end

直到这里你没事。我认为答案是ActiveSupport::Concern