Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class NilUser
def display_name
"Uknown user"
end
end
class Post < ActiveRecord::Base
belongs_to: user, nil_class: NilUser
end
@carlosantoniodasilva

This comment has been minimized.

Copy link

carlosantoniodasilva commented Sep 7, 2012

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

This comment has been minimized.

Copy link
Owner 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

This comment has been minimized.

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

This comment has been minimized.

Copy link

sobrinho commented Sep 10, 2012

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
You can’t perform that action at this time.