jack wrote the following on 30.09.2006 23:32 :
Ok, so I'm lazy, and something about always checking to see if an object
exists before calling one of its methods just strikes me as
In particular, I often do this in code:
if session['user] && session['user'].is_admin
I'd really just like to be able to drop of the session['user'] check. I
mean, if the object doesn't even exist, then the method call can't run,
and the whole thing should probably evaluate to nil, right?
For this kind of things I use a SessionHelper module which the
ApplicationHelper and ApplicationController include.
In the SessionHelper I put things like :
return @cached_user if @cached_user
session[:user_id] ? (@cached_user = User.find(:first,
:conditions => [
'id = ?',
session[:user_id]])) : nil
current_user && current_user.is_admin?
Then you can use
I never store objects in session, only objects' ids to avoid nasty problems.
This is the reason behind the "@cached_user", which effectively limits
current user SQL queries to one by request.
I'm just wondering if there's a smarter way to go about situations like
Simply apply some DRY to your code