views:

729

answers:

2

Hi,

Strange thing – I have Authentication module in lib/ like this:

module Authentication
  protected

  def current_user
    User.find(1)
  end

end

and in ApplicationController I'm including this module and all helpers, but method current_user is available in controllers, but not from views :( How can I make this work?

A: 

Did you declare it with

  helper :foo             # => requires 'foo_helper' and includes FooHelper
  helper 'resources/foo'  # => requires 'resources/foo_helper' and includes Resources::FooHelper

in your ApplicationController?

http://railsapi.com/doc/rails-v2.3.3.1/classes/ActionController/Helpers/ClassMethods.html#M001904

Lichtamberg
i already have in app controllerhelper :allis it not enought?
Alexey Poimtsev
helper :all will only load helpers in the app/helpers dir (and in engine plugins), and I think, only if they're named something_helper.rb / SomethingHelper.
kch
huh, but what about loading a module from lib/ ???
Alexey Poimtsev
Well, then you have to do things a bit more manually. See my answer above.
kch
+4  A: 

If the method were defined directly in the controller, you'd have to make it available to views by calling helper_method :method_name.

class ApplicationController < ActionController::Base

  def current_user
    # ...
  end

  helper_method :current_user
end

With a module, you can do the same, but it's a bit more tricky.

module Authentication
  def current_user
    # ...
  end

  def self.included m
    return unless m < ActionController::Base
    m.helper_method :current_user # , :any_other_helper_methods
  end
end

class ApplicationController < ActionController::Base
  include Authentication
end

Ah, yes, if your module is meant to be strictly a helper module, you can do as Lichtamberg said. But then again, you could just name it AuthenticationHelper and put it in the app/helpers folder.

Although, by my own experience with authentication code, you will want to have it be available to both the controller and views. Because generally you'll handle authorization in the controller. Helpers are exclusively available to the view. (I believe them to be originally intended as shorthands for complex html constructs.)

kch
i've got undefined method `helper_method' for #<Class:0xb139e5c> on m.helper_method :current_user :(((
Alexey Poimtsev
That's weird. I tested the code above. You must be including Authentication in things other than controllers. In that case, just append a condition to that line: if m < ActionController::Base
kch
I updated the example to handle the situation where the module is included in things that are not controllers.
kch