Skip to content

Instantly share code, notes, and snippets.

Created December 27, 2012 18:51
Show Gist options
  • Save anonymous/4390852 to your computer and use it in GitHub Desktop.
Save anonymous/4390852 to your computer and use it in GitHub Desktop.
Ruby struct marshal glitch
class WorkingExample
def initialize
@foo = 1
@bar = 2
end
def marshal_dump
@foo
end
def marshal_load(foo)
@foo = foo
end
end
class FaultyExample < Struct.new(:foo, :bar)
def initialize
super(1, 2)
@qux = 3
end
def marshal_dump
foo
end
def marshal_load(foo)
@foo = foo
end
def inspect
"@foo=#@foo,@bar=#@bar,@qux=#@qux"
end
end
a = WorkingExample.new
puts "WorkingExample before dump and load: #{a.inspect}"
puts "WorkingExample dump #{Marshal.dump(a)}"
puts "WorkingExample after dump and load: #{Marshal.load(Marshal.dump(a)).inspect}"
puts
b = FaultyExample.new
puts "FaultyExample before dump and load: #{b.inspect}"
puts "FaultyExample dump #{Marshal.dump(b)}"
puts "FaultyExample after dump and load: #{Marshal.load(Marshal.dump(b)).inspect}"
=begin
WorkingExample before dump and load: #<WorkingExample:0x007fa18209ca88 @bar=2, @foo=1>
WorkingExample dumpU:WorkingExamplei
WorkingExample after dump and load: #<WorkingExample:0x007fa18209c830 @foo=1>
FaultyExample before dump and load: @foo=,@bar=,@qux=3
FaultyExample dumpIU:FaultyExamplei: @quxi
FaultyExample after dump and load: @foo=1,@bar=,@qux=3
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment