module Gym
def self.included(class_or_module)
class_or_module.send(:include, InstanceMethods)
class_or_module.extend(ClassMethods)
end
module ClassMethods
def build
end
end
module InstanceMethods
def open
end
def book_for_practice
end
def close
end
end
end
这是 RubyMonk 的 Ruby 对象生命周期回调部分中的示例。我不明白它应该如何工作或这样做的意义是什么。 self.included
应该只记录 Gym
中的两个模块如何使用,对吧?为什么 class_or_module
然后被发送/扩展?为什么它不保存在某种记录生命周期的数组中,就像在这个示例中一样,例如
@@extended_objects = []
def self.extended_objects
@@extended_objects
end
def self.extended(class_or_module)
@@extended_objects << class_or_module
最佳答案
这不仅仅是文档。 self.included
是一个回调方法,一旦模块被包含在任何其他模块或类中,就会调用该方法。
在该示例中,实例方法通过 send
包含,类或模块方法通过 extend
包含。
了解更多信息 Ruby documentation .
关于ruby - ruby 中实例和类方法的生命周期回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34374945/