在我的大多數應用程序中,我有一個current_user
方法。爲了避免在例如current_user.name
,current_user
是nil
等情況下出現異常,rails提供try
方法。問題在於我需要記住在current_user
可能是nil
的任何地方使用try
。Rails:使用空對象模式替換嘗試
我想使用空對象模式來消除這種額外開銷。
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
?
不明白爲什麼你似乎也有同感登錄用戶和匿名用戶之間的相同的頁面。爲什麼它不正確地分裂? – apneadiving 2013-04-18 07:43:56