Josef Wolf
9/5/2006 9:41:00 PM
On Tue, Sep 05, 2006 at 07:10:28AM +0900, Logan Capaldo wrote:
[ ... ]
>> AFAICS, the ruby way to store persistent data is YAML. Saving an
>> object with YAML.dump() works like a charm. But I have trouble to
>> read them back with YAML.load(). For some reason, the initialize()
>> method of the loaded object doesn't get called. I don't understand
>> how an object can properly spring in existance without the initialize
>> method?
>
> Well the general purpose of initialize is to set up some state /
> instance variables. That's exactly what the serialized form of the
> object keeps track of anyway.
But what to do when an object needs some resources (this might be a
file/database opened, or, as in my case, a TkCanvas)?
>> For example, I allocate a TkCanvas in the initialize() method. Such
>> an object can not be loaded back properly, IMHO.
>
> Some things aren't serializable in a sane way, that's just a fact of
> life.
I understand that this is not serializable. But wouldn't it be good
to have a chance to reconstruct a new (identical) object from the reloaded
state/instance variables? It need not be the original initialize() method.
It would probably be even better would YAML invoke yaml_initialize() or
something.
>> I have one more problem with such an object: There's no destructor.
>> Should such an object get out of scope, how do I make sure the
>> allocated canvas is destroyed properly?
>
> The garbage collector makes sure that the memory used by objects that
> go out of scope is reclaimed.
It is clear to me that the ruby object is removed by the garbage
collector. But it is not clear what happens to other recources (a
TkCanvas in this case) allocated by this object. Check this out:
#! /usr/bin/ruby
require 'tk'
root=TkRoot.new
class Foo
def initialize
canvas = TkCanvas.new.pack
rect = TkcRectangle.new(canvas, 0, 0, 50, 50, "fill"=>"white")
end
end
begin
x=Foo.new()
end
GC.start
# Object destroyed but canvas and rectangle are still alive
Tk.mainloop
I can't see a solution for this problem since I am a novice for ruby/OO/Tk.
How do you gurus handle such situations?