How to programmatically list all controllers in Rails

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

Leave a Comment