I want to show a post author's name; <% @post.author.name %> works unless author is nil. So I either use unless @post.author.nil? or add a author_name method that checks for nil as in <% @post.author_name %>. The latter I try to avoid.
The problem is that I may need to add/remove words depending on whether there is a value or not. For instance, "Posted on 1/2/3 by " would be the content if I simply display nil. I need to remove the " by " if author is nil.
Null object pattern is one way to avoid this. In your class:
def author
super || build_author
end
This way you will get an empty author no matter what. However, since you don't actually want to have an empty object sometimes when you do expect nil, you can use presenter of some kind.
class PostPresenter
def initialize(post)
@post = post
end
def post_author
(@post.author && @post.author.name) || 'Anonymous'
end
end
Another way is using try, as in @post.author.try(:name), if you can get used to that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With