Superclass mismatch, Struct, reloading and Spork

微笑、不失礼 提交于 2019-12-04 13:45:42

问题


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


来源:https://stackoverflow.com/questions/9785694/superclass-mismatch-struct-reloading-and-spork

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!