简体   繁体   English

在加载时执行类中包含的模块中的代码(而不在初始化时执行)

[英]Execute code in included module in class on load (not on initialize)

I'm working on a project where multiple classes will include MyModule . 我正在一个项目中,其中多个类将包含MyModule Upon including the module, I would like the classes that include the module to push a handle to the class type to a specific class-level array. 包含模块后,我希望包含模块的类将类类型的句柄推送到特定的类级数组。

Psuedocode I've tried below that isn't having the effect I want: 我在下面尝试过的伪代码没有达到我想要的效果:

class Poly
  @@tracking = []
end

module MyModule
  def initialize(klass)
    Poly.tracking << self # Where `self` is the class, e.g. `MyClass1`, not an instance of the class.
  end
end

class MyClass1
  include MyModule
end

class MyClass2
  include MyModule
end

When this is loaded, I'd like for Poly.tracking to equal [MyClass1, MyClass2] . 加载后,我希望Poly.tracking等于[MyClass1, MyClass2]

Here's how I would do it. 这就是我要做的。 Use a class instance variable instead of a class variable. 使用类实例变量而不是类变量。 Add an included method, which is run as a callback when a module is included into the class: 添加一个included方法,当模块包含在类中时该方法作为回调运行:

class Poly
  def self.tracking
    @tracking ||= []
  end
end

module MyModule
  def self.included(base)
    Poly.tracking << base
  end
end

class MyClass1
  include MyModule
end

class MyClass2
  include MyModule
end

puts Poly.tracking.inspect #=> [MyClass1, MyClass2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM