safe_constantize引发异常而不是返回nil

时间:2014-11-14 21:33:21

标签: ruby ruby-on-rails-4 rspec activesupport

def xxx(class)
  cl = "#{class}".safe_constantize
  return '' unless cl
  cl.name
end

我的规范

context 'class exist' do
  it 'return instance of ' do
    xxx("String").should be_eql "String"
  end
end

context 'class does not exist' do
  it 'return empty string' do
    xxx("foo").should be_eql ''
  end
end

然后,当我首先运行我的测试(类存在)时,第二次失败令人惊讶地使用了exeption

Failure/Error: xxx
  NameError:
    uninitialized constant foo

多数民众赞成,因为文件说:

# +safe_constantize+ tries to find a declared constant with the name specified
# in the string. It returns nil when the name is not in CamelCase
# or is not initialized.  See ActiveSupport::Inflector.safe_constantize
#
#   'Module'.safe_constantize  # => Module
#   'Class'.safe_constantize   # => Class
#   'blargle'.safe_constantize # => nil

activesupport(4.1.7)

rspec(2.13.0)

rails(4.1.7)

ruby​​(2.1.2)

我认为save_constantize正在提高返回nil的执行权。

0 个答案:

没有答案