在我的大多数应用程序中,我都有一个current_user
方法。为了避免在类似情况下出现异常current_user.name
where current_user
is nil
,rails 提供了try
方法。问题是我需要记住使用try
无论在哪里current_user
可能nil
.
我想使用空对象模式来消除这种额外的开销。
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
这可以替代try
在某些情况下:
current_user.try(:first_name) #=> nil
current_user.first_name #=> nil
但进一步链接失败:
current_user.profiles.first.name #=> undefined method...
我尝试返回空对象:
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
但在其他情况下这会失败:
current_user.is_admin? #=> #<NullUser:0x96f4e98>
这个问题有可能的解决方案吗?还是我们都必须忍受try
?
我会坚持NullUser
但将其名称更改为GuestUser
让事情变得更清楚。此外,您应该存根 User 类中的所有重要方法,例如
class GuestUser
def method_missing(method_name, *args)
nil
end
def is_admin?
false
end
# maybe even fields:
def name
"Guest"
end
# ...
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)