Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all the mongoid model names in my application

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.

like image 383
Abhay Kumar Avatar asked Jun 02 '12 07:06

Abhay Kumar


4 Answers

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.

like image 78
eltiare Avatar answered Jan 03 '23 22:01

eltiare


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)

like image 25
Steve Avatar answered Jan 03 '23 22:01

Steve


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).

like image 20
Pablo Torrecilla Avatar answered Jan 04 '23 00:01

Pablo Torrecilla


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)

like image 31
Chris Avatar answered Jan 04 '23 00:01

Chris