Class variables with params values ​​in ApplicationController

In the appllication controller, I have several methods that work with the requested controller and action name.

To follow the DRY principle, I want to define common variables with these parameters.

class ApplicationController < ActionController::Base @@requested_action = params[:action] @@requested_controller = params[:controller] end 

But I get the error: undefined local variable or method "params" for ApplicationController:Class

Why can't I do this and how can I achieve my goal?

+4
source share
3 answers

I assume that you already have the controller_name and action_name variables defined by Rails for this purpose.

If you want to do this in your own way, you must define it as a before filter, since the parameters appear only after the request is made. You can do something like this

 class ApplicationController < ActionController::Base before_filter :set_action_and_controller def set_action_and_controller @controller_name = params[:controller] @action_name = params[:action] end end 

You can access them as @controller_name and @action_name. But controller_name and action_name already defined in Rails. You can use them directly.

+4
source

Use instance methods instead:

 class ApplicationController < ActionController::Base def requested_action params[:action] if params end end 
+2
source

You can use the before_filter option.

 class ApplicationController < ActionController::Base before_filter :set_share_variable protected def set_share_variable @requested_action = params[:action] @requested_controller = params[:controller] end end 
+2
source

All Articles