ruby-on-rails - rails : replacing try with the Null Object Pattern

标签 ruby-on-rails ruby design-patterns

在我的大多数应用程序中,我都有一个current_user 方法。为了避免像 current_user.name 这样的情况出现异常,其中 current_usernil,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/

相关文章:

ruby-on-rails - ActiveRecord 自定义字段方法

ruby-on-rails - 如何使用youtube-g ruby gem ?

ruby - 安装 gem Nokogiri-1.8.4 时出错

oop - 何时使用抽象工厂模式?

ruby-on-rails - Geocoder,ip为127.0.0.1时如何在本地测试?

javascript - 在rails中渲染js.erb

ruby - 打印 Ruby block 的源代码

java - 我是否应该使用一种修改后的单例设计模式,只允许对其实例进行一次引用?

java - 在 Java 中使用策略模式的电子邮件程序

ruby-on-rails - 我无法在 Ubuntu 14.02 中使用 ruby​​ 2.2.2 和 Rails 4 运行服务器