Find all the mongoid model names in my application

Is there a way to find out all the names of Mongolian models in a rails application. I can find all the models just by getting all the files in the folder of my applications / models, but I specifically want the mongoid model names.

+4
source share
4 answers

If your model classes are already loaded, you can 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 need 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 get your models to load before launch, you can do it like this (in Rails 3):

 Dir["#{Rails.root}/app/models/**/*.rb"].each { |path| require path } 

(assuming all your models are in app/models or a subdirectory)

+13
source

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

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

+11
source

The problem with Mongoid.models is that it seems to only return 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 create an instance of the Device class 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] 

Thus, this can be a problem, especially if the method is called from a rake task. Chris's solution works fine, so I think this is the best option at the moment: S (I can't work with Steve's solution with Rails 4).

+2
source

Here is the gist I coded to get all Mongolian models and possibly filter them out with superclasses (say, if you want to get only models that inherit from a particular class).

https://gist.github.com/4633211

(compared to Steve's solution, it also works with versions with names)

+1
source

Source: https://habr.com/ru/post/1415691/


All Articles