From: Robert Klemme Date: 2008-05-23T04:40:10+09:00 Subject: Re: customized serialization unreliable???? On 22.05.2008 18:48, sayoyo Sayoyo wrote: > First, Thanks you very much for helping me, Yes, I have tried it, and > the serialization still works randomly. no idea why... > > I suspect the there is a problem in memory allocation somewhere when > data is written to the "file", since it is an random effect, I can > hardly put a hand on it. My gut feeling rather points to an effect caused by different ordering of objects in a Hash. Or you have an issue caused by a loop in your object graph. As far as I can see custom serialization works ok - at least for non complex structures: irb(main):016:0> F = Struct.new :a, :b do irb(main):017:1* def marshal_dump irb(main):018:2> [a,b] irb(main):019:2> end irb(main):020:1> irb(main):021:1* def marshal_load(x) irb(main):022:2> self.a = x[0] irb(main):023:2> self.b = x[1] irb(main):024:2> end irb(main):025:1> end => F irb(main):026:0> x = F.new 1,2 => # irb(main):027:0> s = Marshal.load(Marshal.dump(x)) => # irb(main):028:0> I am not sure why you need custom serialization. But here is an alternative approach: create a method that returns a data structure which you then serialize and add a class method that constructs your in memory structure from that state. E.g. class Foo attr_accessor :name, :size def to_serial [name, size] end def self.from_serial(obj) f = new f.name = obj[0] f.size = obj[1] f end end Of course, this only works if you know what you are deserializing. Another alternative is to separate "configuration state" (which is serializable, e.g. file name) from "operation state" (which is not serializable, e.g. file descriptor) and serialize only the configuration state. This is probably the cleanest approach. > do you know who is the responsible of this part of ruby? You probably can find out by looking at the sources. Kind regards robert