在类中包含模块并执行代码

时间:2009-07-01 13:45:08

标签: ruby inheritance module

以下是我曾经拥有的课程

class Something
    # Defines the validates class methods, which is called upon instantiation
    include Module

    validates :name
    validates :date

end

我现在有几个使用相同功能的对象,更糟糕的是,有几个对象定义了类似的东西,如下所示:

class Anotherthing
    # Defines the validates class methods,  which is called upon instantiation
    include Module

    validates :age

end

我想'重复使用'这些类的内容,所以我把它们变成了模块:

module Something
    # Defines the validates class methods  which is called upon instantiation
    include Module

    validates :name
    validates :date

end

module Anotherthing
    # Defines the validates class methods which is called upon instantiation
    include Module

    validates :age

end

我现在可以创建一个类

class ADualClass
   include Something
   include Anotherthing
end

我遇到的问题是在创建ADualClass对象时没有调用validates方法......似乎永远不会调用“validates:thing”。这是为什么?我怎么强迫这个?

1 个答案:

答案 0 :(得分:14)

在您的模块中,您需要定义,例如

def self.included(base)
  base.validates :name
  base.validates :date
end