2013-04-18 18 views
5

在我的大多數應用程序中,我有一個current_user方法。爲了避免在例如current_user.name,current_usernil等情況下出現異常,rails提供try方法。問題在於我需要記住在current_user可能是nil的任何地方使用tryRails:使用空對象模式替換嘗試

我想使用空對象模式來消除這種額外開銷。

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

+1

不明白爲什麼你似乎也有同感登錄用戶和匿名用戶之間的相同的頁面。爲什麼它不正確地分裂? – apneadiving 2013-04-18 07:43:56

回答

7

我會堅持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