For years and years, I've been writing
@current_user ||= (session[:user_id] && User.find_by_id(session[:user_id]))
The idea was to look up and store the current user object in an instance variable the frst time the method was called, and then use the value in that variable for subsequent calls in the same request.
But now I'm thinking I'll just write this:
session[:user_id] && User.find_by_id(session[:user_id])
Rails already caches query results, so although the find() method will be called on every call to current_user(), the database will only be accessed once, and the user object will only be constructed once. Why complicate my code with optimizations if I haven't yet identified the performance of this method to be an issue?
Is that reckless of me? Or is the ||= a premature optimization which I should train myself out of?