Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically list all controllers in Rails

I'm trying to build a RESTful app to actually manage many kind of configurable objects, so there are a large amount of "resource" types, and hence a lot of controllers. I'm still at the POC phase, so it will be nice if I can show all controllers in a first navigation page, so any easy way (programmable) to do that?

like image 807
Kevin Yu Avatar asked Oct 14 '09 04:10

Kevin Yu


Video Answer


2 Answers

In Rails 3.1+:

Rails.application.routes 

This will give you all the controllers, actions and their routes if you have their paths in your routes.rb file.

For example:

routes= Rails.application.routes.routes.map do |route|   {alias: route.name, path: route.path, controller: route.defaults[:controller], action: route.defaults[:action]} end 

Update: For Rails 3.2, Journal engine path changed, so the code becomes:

routes= Rails.application.routes.routes.map do |route|   {alias: route.name, path: route.path.spec.to_s, controller: route.defaults[:controller], action: route.defaults[:action]} end 

Update: Still working for Rails 4.2.7. To extract the list of controllers (per actual question), you can simply extract the controller and uniq

controllers = Rails.application.routes.routes.map do |route|   route.defaults[:controller] end.uniq 
like image 110
nurettin Avatar answered Sep 22 '22 18:09

nurettin


ApplicationController.subclasses 

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.

like image 21
jdl Avatar answered Sep 23 '22 18:09

jdl