Reputation: 2735
I'm using Ruby on Rails with the following class structure:
class Parent
def self.parse
self.subclasses.each(&:parse) # how to fix this?
end
end
class Child1 < Parent
def self.parse
# ...
end
end
class Child2 < Parent
def self.parse
# ...
end
end
I'd like to do something like:
Parent.parse
=> Child1.parse and Child2.parse
But actually the child classes are not loaded and so the subclasses
methods give empty array.
Is there a easy way to do this very common task?
Upvotes: 2
Views: 898
Reputation: 984
This happens because rails autoloads classes: Parent
doesn't know about its subclasses until they used somewhere or required.
Just require them all manually from the Parent
class:
# parent.rb
require 'child1'
require 'child2'
class Parent
def self.parse
self.subclasses.each(&:parse) # how to fix this?
end
end
Upvotes: 4