Created
September 6, 2012 12:28
-
-
Save KensoDev/3655751 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NilUser | |
def display_name | |
"Uknown user" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Post < ActiveRecord::Base | |
belongs_to: user, nil_class: NilUser | |
end |
@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.
imo you've just overlooked the purpose of the null object pattern and/or the availability of #try in rails.
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
This looks more clear and intention revealing to me.