超类不匹配,结构,重新加载和Spork

问题描述:

假设有以下类

# derp.rb
class Derp < Struct.new :id
end

当I load时。 /derp.rb两次程序失败, TypeError:class class Derp 的超类不匹配。好的,这可以用 require 来管理。但是如何使用Spork为每个测试运行重新加载这样的类? require 显然不会工作,因为它会缓存加载的文件。

When I load "./derp.rb" twice the program fails with TypeError: superclass mismatch for class Derp. Ok, this could be managed with require. But how can I reload such classes for each test run with Spork? require obviously won't work cause it caches the loaded files.

Struct.new 正在为您的每个载入创建新类。

Struct.new is creating new class for your every load.

irb(main):001:0> class Test1 < Struct.new :id; end
nil
irb(main):003:0> class Test1 < Struct.new :id; end
TypeError: superclass mismatch for class Test1
    from (irb):3
    from /usr/bin/irb:12:in `<main>'

您可以保存 Struct.new 返回的 到一个变量,你
可以使用它总是相同 class

You can save your Struct.new returned class to a variable and you can use that will be always the same class.

irb(main):004:0> Id = Struct.new :id
#<Class:0x00000002c35b20>
irb(main):005:0> class Test2 < Id; end
nil
irb(main):006:0> class Test2 < Id; end
nil

或者您可以使用 Struct.new 块样式而不是关键字it
只会给出警告:已经初始化的常量Test3
重新载入您的档案。

or You can use Struct.new block style instead of class keyword it will only give warning: already initialized constant Test3 when you reload your file.

irb(main):023:0> Test3 = Struct.new(:id) do
                     def my_methods
                     "this is a method"
                     end
                   end