Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails: methods from module included in controller not available in view

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?

like image 588
Alexey Poimtsev Avatar asked Aug 12 '09 10:08

Alexey Poimtsev


1 Answers

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.)

like image 117
kch Avatar answered Sep 29 '22 20:09

kch