In rails, I can get the name of the current controller via controller_name and the current action by calling action_name. I am looking for similar runtime reflection for fetching the following:
- List of all controllers in the application.
- List of all actions in a given controller.
For example, I a Product controller which has “add” and “edit” actions. Can I pull the names of these actions programmatically to show the user what operations are supported?
I have looked at a method that calls for use of ActionController::Routing::Routes.named_routes.routes.each
but I could not get that to work. I got uninitialized constant ActionDispatch::Routing::Routes error when I used it.
If there is any good tutorial or document that can help me understand how rails reflection capabilities. I searched for it but I mostly got active record reflection related blogs. I am looking for something that lets me get information on controllers and actions/methods at run time.
Thanks,
Tabrez
The easiest way to get a list of controller classes is:
However, as classes are loaded lazily, you will need to eager load all your classes before you do this. Keep in mind that this method will take time, and it will slow down your boot:
To get all the actions in a controller, use
action_methodsThis will return a
Setcontaining a list of all of the methods in your controller that are “actions” (using the same logic Rails uses to decide whether a method is a valid action to route to).