[英]Ruby on Rails - Call a method for each subclass from the parent class
I'm using Ruby on Rails with the following class structure: 我正在使用具有以下类结构的Ruby on Rails:
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. 但是实际上未加载子类,因此subclasses
方法给出了空数组。
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. 发生这种情况是因为Rails会自动加载类: Parent
类直到其子类在某个地方使用或必需时才知道其子类。
Just require them all manually from the Parent
class: 只需从Parent
类手动要求它们:
# parent.rb
require 'child1'
require 'child2'
class Parent
def self.parse
self.subclasses.each(&:parse) # how to fix this?
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.