Friday 18 May 2012

Get models and controllers list inside rails application


Get collection of models inside your application.


 1. Get table names inside database 

  ActiveRecord::Base.connection.tables.map do |model|
    model.capitalize.singularize.camelize
  end

  =>["Blog", "User", "UserDetail"]


 2. Load models dir

  @models = Dir['app/models/*.rb'].map {|f| File.basename(f, '.*').camelize.constantize.name }


 3. ActiveRecord subclasses
     It will only get base class models not inherited models.

# make sure that  relevant models are loaded otherwise
# require them prior
# Dir.glob('#{RAILS_ROOT}/app/models/*.rb').each { |file| require file }
   class A < ActiveRecord::Base
   end

   class B < A
   end

   class C < B
   end

  ActiveRecord::Base.subclasses.each{|x| x.name }

  =>["A"] 


 4. Inherited model
     It will get both base class models and inherited models using descendants.

# make sure that  relevant models are loaded otherwise
# require them prior
# Dir.glob('#{RAILS_ROOT}/app/models/*.rb').each { |file| require file }
   class A < ActiveRecord::Base
   end

   class B < A
   end

   class C < B
   end

  ActiveRecord::Base.descendants.each{|x| x.name }

  =>["A", "B", "C"]


Get collection of controllers inside your application.


 1. ApplicationController subclasses
     It will get all controller classes.

  ApplicationController.subclasses

  =>["AccountsController", "BlogsController", "UsersController"]


 2. Inherited Controller
      It is get all controller classes along with inherited controller classes.

  class AccountsController < ApplicationController
  end

  class ArticlesController < ::AccountsController
  end

  ApplicationController.descendants

  =>["AccountsController", "BlogsController", "UsersController", "AccountsController", "ArticlesController"]


Note:
   require all files in "#{RAILS_ROOT}/app/controllers" to populate your list in development mode.
   It'll get you started, but keep in mind that in development mode you won't see much, because it will only show you what's actually been loaded. Fire it up in production mode, and you should see a list of all of your controllers.



To get all the actions in a controller, use action_methods



  PostsController.action_methods