In appllication controller i have couple of methods that works with requested controller and action name.
To follow DRY principe, i want to define share variables with those params.
class ApplicationController < ActionController::Base
@@requested_action = params[:action]
@@requested_controller = params[:controller]
end
But i get error: undefined local variable or method "para开发者_JAVA技巧ms" for ApplicationController:Class
Why i can't do this and how can i achieve my goal?
I believe you already have controller_name
and action_name
variables defined by Rails for this purpose.
If you want to do it by your way, you must define it as a before filter as params comes to existence 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
are already defined in Rails. You can use them directly.
Use instance methods instead:
class ApplicationController < ActionController::Base
def requested_action
params[:action] if params
end
end
You can use 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
精彩评论