Find all the mongoid model names in my application

2019-05-06 22:49发布

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.

4条回答
【Aperson】
2楼-- · 2019-05-06 23:20

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 }

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 }

(assuming all of your models are in app/models or a sub-directory)

查看更多
ら.Afraid
3楼-- · 2019-05-06 23:29

The problem with Mongoid.models is that apparently only returns the already loaded models. I did the following experiment in the rails console (I have three models: Admin, User and Device):

irb(main)> Mongoid.models
=> [Admin, User]

But if I instantiate the class Device and then call the same method, I get a different result:

irb(main)> Device.last
=> #<Device _id: 52c697494d616308cf380000, type_code: "666", name: "My device">
irb(main)> Mongoid.models
=> [Admin, User, Device]

So this could represent a problem, specially if the method is called from a rake task. The Chris' solution works fine so I guess that is the best option at this moment :S (I can't got working the Steve's solution with Rails 4).

查看更多
Juvenile、少年°
4楼-- · 2019-05-06 23:31

You can do this in Mongoid version 3.1 and higher: Mongoid.models

If you are in Rails' development mode where the models are not automatically loaded, run Rails.application.eager_load! to load the entire application.

查看更多
我想做一个坏孩纸
5楼-- · 2019-05-06 23:32

Here is a gist I coded to get all Mongoid models, and optionally filter them by superclass (say, if you want to only get models inheriting from a specific class).

https://gist.github.com/4633211

(compared to Steve solution, it's also working with namespaced models)

查看更多
登录 后发表回答