What you’ve got there is an instance variable, but it’s an instance
variable that belongs to the class object, ApplicationController,
itself. Like so many things in Ruby, it comes down to: classes are
objects too
What you want are instance variables that belong to the particular
instance of the controller that gets created and runs the action. You
can do this using a before_filter hook:
class ApplicationController < ActionController::Base
before_filter :set_user
def set_user @current_user = User.find(session[:user_id])
end
end
etc. You’d probably want to limit it to certain actions, but you can
do that too. (See API docs for before_filter and other related
methods.)
Notice that @current_user is inside an instance method definition. So
when that code gets executed, it will be in the context of a
particular instance of ApplicationController, and that instance will
own the instance variable.
Great, this works too and I’ll use it. I like that it doesn’t get set
until
I call for the variable. The only thing is I can’t restrict it to
certain
actions but for my purposes this doesn’t matter because I’m only calling
it
from actions where I need it so that’s good enough.
class ApplicationController < ActionController::Base
before_filter :set_user
def set_user @current_user = User.find(session[:user_id])
end
end
You could also do this:
class ApplicationController < ActionController::Base
protected
def current_user
@current_user ||= User.find(session[:user_id])
end
helper_method :current_user
end
Which means that you don’t look for the current user until you
actually need to, that the implementation of getting the current user
is hidden a little better, and lets you type one less character to
type when getting the current user.
This probably isn’t kosher – controller variables should be set from
inside controllers, not layouts… but it’s neat enough that I wish
there were a good reason to use it… you could include this in your
layout:
Great, this works too and I’ll use it. I like that it doesn’t get set
until I call for the variable. The only thing is I can’t restrict it
to certain actions but for my purposes this doesn’t matter because I’m
only calling it from actions where I need it so that’s good enough.
Thanks,
Jeff
if you want to restrict access to certain actions then i suggest you
take a look at ActiveRBAC [0] which will allow you to quite easily
specify such restrictions, like this:
def protect_controller_to_role( role )
if !session[:rbac_user_id].nil? and
User.find(session[:rbac_user_id]).has_role?( “Admin”, role )
return true
else
redirect_to ‘/q/list’
flash[:notice] = “You are not allowed to access this page”
return false
end
end
def protect_controller
protect_controller_to_role(“BasicUser”)
end
end
the above restricts access to all actions in the controller except for
list, index and show, unless they have been granted the Admin or
BasicUser role.
have a look at the manual [1] for more information on what can be done.