在Rails中获取所有子类数组是一个常见的需求,特别是在实现多态行为或需要动态加载类时。以下是完整的解决方案:
Ruby的Class类提供了descendants
方法,可以获取所有直接子类。在Rails中,由于开发环境会延迟加载类,需要特别注意加载时机。
ParentClass.descendants
# 返回所有直接子类的数组
如果子类尚未加载,需要先强制加载所有文件:
# 在config/initializers/preload_classes.rb
Rails.application.config.after_initialize do
Dir.glob(Rails.root.join('app/models/**/*.rb')).each { |f| require f }
end
def all_descendants(parent)
parent.descendants.flat_map { |child| [child] + all_descendants(child) }
end
all_descendants(ParentClass)
假设有继承结构:
class Vehicle; end
class Car < Vehicle; end
class Truck < Vehicle; end
class Sedan < Car; end
获取所有子类:
Vehicle.descendants
# => [Car, Truck, Sedan] (注意顺序可能不同)
如果只需要类名而不需要实际类对象:
ObjectSpace.each_object(Class).select { |c| c < ParentClass }
以上方法在Rails 5+和Ruby 2.4+环境中测试有效,对于更复杂的继承结构也能正常工作。
没有搜到相关的文章