在我的大多数应用程序中,我都有current_user
方法。为了避免在current_user.name
current_user
为nil
的情况下出现异常,rails提供了try
方法。这样做的问题是,我需要记住在try
可能current_user
的任何地方使用nil
。
我想使用Null Object模式来消除这种额外的开销。
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...
我试图返回null对象:
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
?
答案 0 :(得分:8)
我会坚持使用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
答案 1 :(得分:3)
如果您希望能够在NullUser
个实例上链接方法,则需要method_missing
返回self
而不是nil
。您尝试返回self.class.new
已关闭...
Avdi Grim explains how to implement a Null Object pattern in Ruby.