Sunday, January 18, 2009

A matter of style...


I've seen plenty of code examples that show how to set the current user or subdomain to a variable. For example:


1
2
3
4
5
6
7
8
class ProfileController < ActionController::Base
before_filter :set_current_user

private
def set_current_user
@current_user = User.find_by_username(session[:username]) if session[:username]
end
end


However, I prefer this way:


1
2
3
4
5
6
7
class ProfileController < ActionController::Base
private
def current_user
@current_user ||= User.find_by_username(session[:username]) if session[:username]
end
helper_method :current_user
end


With this technique, I always use the current_user method to determine the current user, and never reference the @current_user variable. If an action doesn't need to know the current_user, no time is wasted to set it.

0 comments: