我有两个几乎相同的模型。我想创建一个或多个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
现在如何提取常量和验证方法?
答案 0 :(得分:0)
常量包含在include
中,validates
方法族也是实例方法所以......
module ModelInstanceMethods
STATUS_OPTIONS = ['new', 'approved', 'rejected', 'deleted']
def simple_instance_method
'easy'
end
end
直到这里你没事。我认为答案是ActiveSupport::Concern