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].

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.