Superclass mismatch, Struct, reloading and Spork

2019-03-20 12:17发布

Suppose there's the following class

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

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.

3条回答
Rolldiameter
2楼-- · 2019-03-20 12:31

For those finding this on Google, this is what solved it for me:

module MyModule
  class MyClass
    MyClassStruct ||= Struct.new(:id)
    SomeStruct < MyClassStruct
    ...
  end
end
查看更多
冷血范
3楼-- · 2019-03-20 12:35

You can make sure the struct class is created only once.

Test1 < $test1 ||= Struct.new(:id)

查看更多
Bombasti
4楼-- · 2019-03-20 12:42

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>'

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

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
查看更多
登录 后发表回答