In most of my applications, I have a current_user method. To avoid exceptions in cases such as current_user.name , where current_user is nil , the rails provide a try method. The problem is that I need to remember to use try wherever current_user can be nil .
I want to use the Null Object pattern to remove this extra overhead.
class NullUser def method_missing(method_name, *args) nil end end def current_user return NullUser.new unless UserSession.find @current_user ||= UserSession.find.user end
In some cases, this may replace try :
current_user.try(:first_name)
but with further closure it doesnβt work:
current_user.profiles.first.name
I tried to return a null object:
class NullUser def method_missing(method_name, *args) self.class.new end end current_user.try { |u| u.profiles.first.name } #=> nil current_user.profiles.first.name #=> nil
but this will fail in other cases:
current_user.is_admin? #=> #<NullUser:0x96f4e98>
Is there a possible solution to this problem or should we all live with try ?
source share