有没有办法在您的 Rails 应用程序中获取所有模型的集合? [英] Is there a way to get a collection of all the Models in your Rails app?
问题描述
有没有一种方法可以让您获得 Rails 应用中所有模型的集合?
Is there a way that you can get a collection of all of the Models in your Rails app?
基本上,我可以这样做:-
Basically, can I do the likes of: -
Models.each do |model|
puts model.class.name
end
推荐答案
查看评论和其他答案.还有比这个更聪明的答案!或者尝试将其作为社区 wiki 进行改进.
模型不会将自己注册到主对象,所以不,Rails 没有模型列表.
Models do not register themselves to a master object, so no, Rails does not have the list of models.
但是您仍然可以查看应用程序模型目录的内容...
But you could still look in the content of the models directory of your application...
Dir.foreach("#{RAILS_ROOT}/app/models") do |model_path|
# ...
end
另一个(疯狂的)想法是使用 Ruby 反射来搜索每个扩展 ActiveRecord::Base 的类.虽然不知道如何列出所有课程...
Another (wild) idea would be to use Ruby reflection to search for every classes that extends ActiveRecord::Base. Don't know how you can list all the classes though...
只是为了好玩,我找到了一种列出所有类的方法
Just for fun, I found a way to list all classes
Module.constants.select { |c| (eval c).is_a? Class }
终于在不查看目录的情况下成功列出了所有模型
Finally succeeded in listing all models without looking at directories
Module.constants.select do |constant_name|
constant = eval constant_name
if not constant.nil? and constant.is_a? Class and constant.superclass == ActiveRecord::Base
constant
end
end
如果你也想处理派生类,那么你需要测试整个超类链.我是通过在 Class 类中添加一个方法来实现的:
If you want to handle derived class too, then you will need to test the whole superclass chain. I did it by adding a method to the Class class:
class Class
def extend?(klass)
not superclass.nil? and ( superclass == klass or superclass.extend? klass )
end
end
def models
Module.constants.select do |constant_name|
constant = eval constant_name
if not constant.nil? and constant.is_a? Class and constant.extend? ActiveRecord::Base
constant
end
end
end
这篇关于有没有办法在您的 Rails 应用程序中获取所有模型的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!