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

前端之家收集整理的这篇文章主要介绍了ruby – 在类中包含模块并执行代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我以前的课程
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”.这是为什么?我怎么强迫这个?

解决方法

在您的模块中,您需要定义,例如
def self.included(base)
  base.validates :name
  base.validates :date
end

猜你在找的Ruby相关文章