在我的应用程序中找到所有蒙古型模型名称 [英] Find all the mongoid model names in my application
问题描述
有没有办法在我的rails应用程序中找出所有Mongoid模型名称.我可以通过将所有文件放到我的app/models文件夹中找到所有模型,但是我特别想要蒙古模型名称.
Is there a way to find out all the Mongoid Models names in my rails app. I can find all the models just by getting all the file inside my app/models folder but i specifically want mongoid model names.
推荐答案
如果已经加载了模型类,则可以通过找到所有包含Mongoid :: Document模块的类来列出它们.
If your model classes are already loaded then you could list them by finding all the classes that include the Mongoid::Document module.
Object.constants.collect { |sym| Object.const_get(sym) }.
select { |constant| constant.class == Class && constant.include?(Mongoid::Document) }
或者如果您只想要类名:
or if you just want the class names:
Object.constants.collect { |sym| Object.const_get(sym) }.
select { |constant| constant.class == Class && constant.include?(Mongoid::Document) }.
collect { |klass| klass.name }
如果需要在运行之前强制加载模型,可以这样做(在Rails 3中):
If you need to force your models to load before running this you can do so like this (in Rails 3):
Dir["#{Rails.root}/app/models/**/*.rb"].each { |path| require path }
(假设所有模型都在app/models
或子目录中)
(assuming all of your models are in app/models
or a sub-directory)
这篇关于在我的应用程序中找到所有蒙古型模型名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!