ruby - ruby 中实例和类方法的生命周期回调

标签 ruby metaprogramming

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/

相关文章:

c++ - 使用 Boost Hana 处理部分类型

ruby - 为什么我不能在 Object 实例的单例类中包含 Kernel

ruby-on-rails - 无法运行 rake db :migrate

ruby - 在 Puppet 中将变量转换为字符串

java - 桌面应用程序的自动化击键

ruby - 在 Ruby 中覆盖 "for"关键字。是否可以?

c++ - 派生类能够访问其基类的私有(private)成员

mysql 数据库我该如何解决这个问题?

ruby - 立即从控制台获取单个字符

C++ 模板元编程——根据运行时输入返回一个类型