无法解救NameError

时间:2014-10-05 20:35:33

标签: ruby

有人可以告诉我这里我做错了吗?

wtf.rb

require 'minitest/autorun'

class MyPlugin
  def self.valid_plugin?(plugin_class)
    begin
      plugin_class.ancestors.include?(self)
    rescue NameError
      false
    end
  end
end

class MyPluginTest < Minitest::Test
  def test_valid_plugin_handles_missing_constant
    assert_equal false, MyPlugin.valid_plugin?(MyMissingConstant)
  end
end

环境

$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0]

$ gem list --local

*** LOCAL GEMS ***

bigdecimal (1.2.4)
bundler (1.7.3)
io-console (0.4.2)
json (1.8.1)
minitest (5.4.2, 4.7.5)
psych (2.0.5)
rake (10.1.0)
rdoc (4.1.0)
test-unit (2.1.2.0)

$ ruby wtf.rb
Run options: --seed 32486

# Running:

E

Finished in 0.001228s, 814.3322 runs/s, 0.0000 assertions/s.

  1) Error:
MyPluginTest#test_valid_plugin_handles_missing_constant:
NameError: uninitialized constant MyPluginTest::MyMissingConstant
    wtf.rb:15:in `test_valid_plugin_handles_missing_constant'

1 runs, 0 assertions, 0 failures, 1 errors, 0 skips

1 个答案:

答案 0 :(得分:3)

在调用MyMissingConstant方法之前评估

valid_plugin?。您必须在呼叫站点进行救援,或者传递一个字符串并在方法中查找常量。

Kernel.const_get可能是最简单的方法。有关详细信息,请查看问题:

How to convert a string to a constant in Ruby?