Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Superclass mismatch, Struct, reloading and Spork

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.

like image 243
synapse Avatar asked Mar 20 '12 11:03

synapse


3 Answers

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
like image 127
Selman Ulug Avatar answered Nov 02 '22 23:11

Selman Ulug


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

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

like image 38
Andreyy Avatar answered Nov 02 '22 23:11

Andreyy


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
like image 1
dignoe Avatar answered Nov 03 '22 01:11

dignoe