Rails:用Null对象模式替换try

在我的大多数应用程序中,我有一个current_user方法。 为了避免在current_user.name其中current_usernil情况下出现exception,rails提供了try方法。 这个问题是我需要记住在current_user可能nil地方使用try

我想使用Null对象模式来消除这个额外的开销。

 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? #=> # 

有没有可能解决这个问题的方法,还是我们都必须忍受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 

如果您希望能够在NullUser实例上链接方法,则需要让method_missing返回self而不是nil 。 您尝试返回self.class.new已关闭…

Avdi Grim解释了如何在Ruby中实现Null对象模式。