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:
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 Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.
Before Filters ADVERTISEMENT. ADVERTISEMENT. Rails before filters are executed before the code in action controller is executed. The before filters are defined at the top of a controller class that calls them. To set it up, you need to call before_filter method.
Ruby on Rails defines seven standard controller actions can be used to do common things such as display and modify data. If you only want to create routes for specific actions, you can use :only to fine tune the resource route. This line maps URLs only to the Message controller's index and show actions.
Action Controllers are the core of a web request in Rails. They are made up of one or more actions that are executed on request and then either it renders a template or redirects to another action.
The easiest way to get a list of controller classes is:
ApplicationController.descendants
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:
Rails.application.eager_load!
To get all the actions in a controller, use action_methods
PostsController.action_methods
This will return a Set
containing 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With