iJK
iJK

Reputation: 4755

using helpers properly in ruby on rails

It looks like you cannot use a helper in a controller even if both of them belong to the same class. For example: XYZHelper and XYZController...

I was under the impression that if the prefix is the same "XYZ" then the method in the helper can be used in the controller and in the view, but I think this is not the case.

So how do I remove some common functionality from a controller and place it in a helper. I want to place that piece of code in a helper because other controllers may be using it. What is the best way to approach this.

Thanks, Jai.

Upvotes: 1

Views: 299

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64363

Follow Pete's guidelines. If you still need to expose the methods then do the following:

Add the methods to ApplicationController class and register the methods as helper methods by calling helper_method.

class ApplicationController < ActionController::Base

  helper_method :foo, :bar

private

  def foo
   "foo"
  end 

  def bar
   "bar"
  end 
end

Upvotes: 0

Pete
Pete

Reputation: 18075

There are a few ways you could share some code between controllers:

  1. Application controller: If the code in question is an action/method which ought to be in a controller, but could be used by several controllers (or all of them), then this might be a place to put it.

  2. the 'lib' directory. just a general purpose place to put code which should be shared.

  3. Put it in the model. This may or may not be applicable, but its worth taking a good look at the code you're trying to move and thinking about whether it is something which makes sense on a model (instead of a controller or random class/module in lib).

Upvotes: 1

Related Questions