Difference between false and :false

I was noticing that some code (acts_as_authenticated in particular) uses the symbol :false. What is the purpose of this symbol? Why not just use false? How can I write and if blog that will not be triggered if the variable is :false?

Thanks, Jim

:false is just a symbol that has no special meaning. It has nothing in common with false. I assume you’re referring to this line in the current_user method of acts_as_authenticated/restful_authentication:

@current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie || :false)

The reason it uses :false instead of false is because the shorthand assignment (||=) would re-evaluate all the login methods every time #current_user was called if the user was not logged in.

I think the use of :false is nasty and it should be rewritten to use something like:

unless @current_user == false @current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie || false)

end

Hope that clears it up.

Brandon

Yes, it is downright evil. However, I disagree on how to clean up this mess. This is really a classic situation for using the Null Object Pattern in order to avoid special cases for non-existent (nil) or otherwise absent (:false) objects. A Null Object is simply a real object of the appropriate (duck) type

  def current_user     @current_user ||= (login_from_session || login_from_basic_auth ||       login_from_cookie || guest_user)   end

  def guest_user     GuestUser.new   end

  def logged_in?     current_user.logged_in?   end

  class GuestUser     def logged_in?       false     end     def active?       true     end     # whatever other methods you need     ...   end    With this, you can always be certain that you get a sensible (not nil) result from current_user, can call methods on it and don't have to care whether it is a real, logged-in user or a guest.

Michael

Michael Schuerig wrote:

  def current_user     @current_user ||= (login_from_session || login_from_basic_auth ||       login_from_cookie || guest_user)   end

  class GuestUser     def logged_in?       false

...

With this, you can always be certain that you get a sensible (not nil) result from current_user, can call methods on it and don't have to care whether it is a real, logged-in user or a guest.

+1.

I used exactly that on every Rails project I ever did, and it never gets old. There's just no way to describe the freedom of writing...

   def index      @favorite_posts = Post.find_by_tags(someone.tags)    end

...and not give a second thought to whether 'someone' is a guest, a logged-in user, or a premium user. And you write 'someone...' in sooo many places!