ruby - Rails: replacing try with the Null Object Pattern -
in of applications, have current_user
method. avoid exceptions in cases current_user.name
current_user
nil
, rails provides try
method. problem need remember use try
wherever current_user
might nil
.
i want use null object pattern remove additional 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
this can replace try
in cases:
current_user.try(:first_name) #=> nil current_user.first_name #=> nil
but fails further chaining:
current_user.profiles.first.name #=> undefined method...
i tried return 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 fail in other cases:
current_user.is_admin? #=> #<nulluser:0x96f4e98>
is there possible solution problem or have live try
?
i stick nulluser
change name guestuser
make things clearer. additionally should stub important method user class, e.g.
class guestuser def method_missing(method_name, *args) nil end def is_admin? false end # maybe fields: def name "guest" end # ... end
Comments
Post a Comment