3

I'm working on a project where multiple classes will include 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].

bdx
  • 3,316
  • 4
  • 32
  • 65

1 Answers1

6

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:

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]
Community
  • 1
  • 1
infused
  • 24,000
  • 13
  • 68
  • 78
  • Very succinct. My understanding of instance variables in ruby is clearly lacking, that doesn't fit with how I understood they worked (mainly coming from a rails perspective). Thanks for the link, I'm going to go through that until I understand where I've gone wrong. – bdx May 13 '15 at 05:43