Superclass mismatch, Struct, reloading and Spork

2019-03-20 12:33发布

问题:

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.

回答1:

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


回答2:

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

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



回答3:

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