JZ.
JZ.

Reputation: 21877

How to list all models in a Rails project from the context of a gem?

I'm trying to determine how to do two simple tasks:

  1. I would like to load all of a Rails Apps' models from the context of a Gem. For example say the Rails application is a blog and has authors, posts and comments. I would like the included gem to find, without knowing they exist, those models.

  2. Again, from the context of a loaded gem, I would like to have the rails models available to me; So for example I could call Author.first, without knowing Authors exist, and I would like to have that information available to the gem.

So to summarize this question. From the context of a gem, how does one load all models of a rails project, and have access to those models?

This is my fast hack:

module ActiveTest
  class Base
    def listme
      ::ActiveRecord::Base.subclasses.collect { |type| type.name }.sort
    end
  end
end


1.9.3-p286 :005 > a = ActiveTest::Base.new
 => #<ActiveTest::Base:0x007f8882bdd460> 
1.9.3-p286 :006 > a.listme
    NameError: uninitialized constant ActiveRecord

Upvotes: 2

Views: 1760

Answers (1)

Kyle
Kyle

Reputation: 22258

Using ActiveSupport

models = Dir["#{Rails.root}/app/models/**/*.rb"].map do |f|
  f.chomp('.rb').camelize # works with namespaces e.g. Foo::Bar::MyClass
end

If you want to turn those strings into the actual Class objects, tack on a constantize right after camelize

camelize docs

constantize docs

Upvotes: 4

Related Questions