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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.