I want the following module to be included in a class I have:
module InheritanceEnumerator
def self.included(klass)
klass.instance_eval do
instance_variable_set('@subclasses',[])
def self.subclasses
@subclasses
end
original_method = self.respond_to?(:inherited) ? self.public_method(:inherited) : nil
instance_variable_set('@original_inherited_method', original_method)
def self.inherited(subclass)
@original_inherited_method.call(subclass) if @original_inherited_method
@subclasses<<subclass
end
end
end
end
What I’m trying to achieve is that I want my parent class to have references to direct children. I also need any other previous “inherited” methods set on my class by other stuff to stay in place. What am I doing wrong?
Your code works in this situation (for me):
But fails in the following situation:
This is because you are only initializing
@subclasseswhen the module is included; but you are forgetting that subclasses ofCalso have access to the modules methods but do not explictlyincludeit.You fix this by doing the following:
EDIT:
Okay, in future, please state what your problem is more fully and provide the test code you are using; as this was an exercise in frustration.
The following works fine with your code:
Perhaps the reason it wasn’t working for you is that you included
InheritanceEnumeratorbefore you had defined theinheritedmethod?