4

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 "params" for ApplicationController:Class

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

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. Testing with Rails 4.2.1, in the ApplicationController but outside of a before_filter, controller_name is "application"; action_name and params don't exist. Inside a before_filter, controller_name corresponds to the controller that is being loaded and the other two are also set. So the comment about params not coming into existence until the request is made is still valid.
2

Use instance methods instead:

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.