Reputation: 367
I am attempting to use a gem that requires me to access the current user that is logged in through a controller extension. Here is my ApplicationController with what I thought should work:
class ApplicationController < ActionController::Base
helper :all
protect_from_forgery
set_current_tenant_to(current_user.member)
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
def require_user
unless current_user
flash[:notice] = "You must be logged in to access this page"
redirect_to '/login'
return false
end
end
end
This fails on the set_current_tenant_to with "undefined local variable or method `current_user' for ApplicationController:Class".
Is there any way to get access to the current_user method through a controller extension?
Thanks for your help!
Upvotes: 0
Views: 2174
Reputation: 10823
The problem here is with the scope: if you're defining current user as an instance method, it will be available to all instances of the controller (which are created on every url request), but you are trying to use it as a class method.
So to define it as a class method:
def self.current_user
...
end
but it has no sense without the request, and it has even less sense because classes will be cashed in production, and set_current_tenant_to will be called only once on server start.
PS sorry for necroposting, I've just seen there is no answer here
Upvotes: 3
Reputation: 3143
Your helper is in the private section -- you want that outside of the private block
Upvotes: 1