模块的included()
模块的included方法会在其他的类或模块把这个模块混入他们自己里面时被调用,调用时传入的参数为混入模块的模块或类,如下代码
module A
def A.included(mod)
puts "#{self} is included in #{mod}"
end
end
module B
include A
end
当B混入A时,此时A的included方法会被调用,通常我们见到的为类设置他的实例方法和类方法的代码如下
module A
def A.included(mod)
def mod.method
puts "this is the class method"
end
end
def method
puts "this is the instance method"
end
end
class B
include A
end
b=B.new
b.method
B.method
输出结果为: this is the instance method this is the class method 当B混入A时,A.included方法被调用,参数为B,该方法中设置了B的method方法,而随着B混入A,A中的实例方法method也作为了B中的实例方法。从而实现了为B同时设置实例方法和类方法