Skip to content

Instantly share code, notes, and snippets.

@KensoDev
Created September 6, 2012 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KensoDev/3655751 to your computer and use it in GitHub Desktop.
Save KensoDev/3655751 to your computer and use it in GitHub Desktop.
class NilUser
def display_name
"Uknown user"
end
end
class Post < ActiveRecord::Base
belongs_to: user, nil_class: NilUser
end
@carlosantoniodasilva
Copy link

class NilUser
  def display_name
    "Uknown user"
  end
end

class Post < ActiveRecord::Base
  belongs_to: user

  # Can add some instance variable caching if necessary.
  def user
    super || NilUser.new
  end
end

This looks more clear and intention revealing to me.

@KensoDev
Copy link
Author

KensoDev commented Sep 8, 2012

@carlosantoniodasilva I know it can be done this way, but it's too verbose to do it for every class, IMHO this is a better option

class Post < ActiveRecord::Base
  belongs_to :user, nil_class: NilUser
end

I would actually go even further then that (needs to be accepted by core members of course)

class Post < ActiveRecord::Base
  belongs_to :user #Will try to load NilUser.new if nil automatically

From what I have seen done in rails over the years is that the first option is done first and the second later.

@krupenik
Copy link

krupenik commented Sep 9, 2012

imo you've just overlooked the purpose of the null object pattern and/or the availability of #try in rails.

@sobrinho
Copy link

class Post < ActiveRecord::Base
  belongs_to :user

  def author
    user.try(:name)
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment