有一种方法来获取所有的模型在你的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
推荐答案
编辑:查看评论和其他答案。有比这更聪明的答案!
Look at the comments and other answers. There are smarter answers than this one! Or try to improve this one as community wiki.
模型不会自己注册到主对象,所以没有,Rails没有模型列表。
Models do not register themselves to a master object, so no, Rails does not have the list of models.
但你仍然可以查看你的应用程序的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屋!