在我的大多数应用程序中,我都有一个current_user
方法。为了避免像 current_user.name
这样的情况出现异常,其中 current_user
是 nil
,rails 提供了 try
方法。这个问题是我需要记住在 current_user
可能是 nil
的地方使用 try
。
我想使用 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...
我试图返回空对象:
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
以使事情更清楚。此外,您应该 stub User 类中的所有重要方法,例如
class GuestUser
def method_missing(method_name, *args)
nil
end
def is_admin?
false
end
# maybe even fields:
def name
"Guest"
end
# ...
end
关于ruby-on-rails - rails : replacing try with the Null Object Pattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16077115/