Rails:用Null对象模式替换try [英] Rails: replacing try with the Null Object Pattern

查看:110
本文介绍了Rails:用Null对象模式替换try的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的大多数应用程序中,我有一个 current_user 方法。为了避免例如 current_user.name 其中 current_user nil ,rails提供 try 方法。这个问题是我需要记住使用 try where current_user 可能是 nil

In most of my applications, I have a current_user method. To avoid exceptions in cases like current_user.name where current_user is nil, rails provides the try method. The problem with this is that I need to remember to use try wherever current_user might be nil.

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

I want to use the Null Object pattern to remove this additional overhead.

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

This can replace try in some cases:

current_user.try(:first_name)     #=> nil
current_user.first_name           #=> nil

但进一步链接失败:

current_user.profiles.first.name    #=> undefined method...






我试图返回null对象:


I tried to return the null object:

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

但在其他情况下会失败:

but this would fail in other cases:

current_user.is_admin?            #=>  #<NullUser:0x96f4e98>

有没有可能的解决这个问题,或者我们都必须生活在尝试

Is there a possible solution to this problem or do we all have to live with try?

推荐答案

我会坚持使用 NullUser ,但将其名称更改为 GuestUser 以使事情更清晰。此外,您应该从您的用户类中存储所有重要的方法,例如

I would stick with the NullUser but change its name to GuestUser to make things clearer. Additionally you should stub all important method from your User class, e.g.

class GuestUser
  def method_missing(method_name, *args)
    nil
  end

  def is_admin?
    false
  end

  # maybe even fields:
  def name
    "Guest"
  end

  # ...
end

这篇关于Rails:用Null对象模式替换try的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆