Execute code in included module in class on load (not on initialize)
我正在研究一个项目,其中多个类将包括
我在下面尝试的psuedocode没有我想要的效果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
加载后,我希望
我会这样做的。使用类实例变量而不是类变量。添加一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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] |