From: Charles Hixson Date: 2003-11-15T01:56:37+09:00 Subject: Re: Singletons and Marshalling That sure *looks* good. It looks as if with only quite minor changes it will do exactly what I was hoping for. Christoph wrote: >------------ >/Christoph > >Please send off list mail to >'my_mail@gmy.net'.gsub(/y/,'x') > > > > > >>-----Original Message----- >>From: Charles Hixson [mailto:charleshixsn@earthlink.net] >>Sent: Friday, 14 November, 2003 04:37 AM >>To: ruby-talk ML >>Subject: Singletons and Marshalling >> >>Does anyone know how singleton's and marshalling interact? Be dumped >> >>In particular, I want to have my singleton class be able to >>dump and load (and be saved on a file). So I'm wondering if >>there are any methods to be implemented that would enable this. >> >>In particular, I'm composing a kind of container class that >>will contain >>either an array, a hash, or possibly both of values. >>Dumping it should >>be basically dumping all the members of the hash/array (plus >>a few more), and restoring should append the contents of the >>being-restored value to the one in memory. (Duplicates >>aren't a problem as they'll just be dropped.) >> >> > >Since you are - pause - not worried about duplicates, you are >probably talking about pattern singletons? Duplicates, even private >Ones, are sort of bad style in Ruby, since you can easily access the >duplicates with ObjectSpace#each_object - therefore it might >have better to right out outlaw any kind of duplicates, but this >not in keeping with the standard pattern singleton definition >(developed for less dynamic languages). > > > >>If this can't be done, there are other approaches, but as >>they involve things like private class variables & classes >>that are only used internally as a cache.... well, the other >>approach looks cleaner, if it's possible. >> >> > >Here is the marshaling example from (1.8) singleton.rb adopted >to your situation - does this do what you want? > ># example >require 'singleton' > >class A > include Singleton > > def initialize > @hsh = {} > @ary = [] > end > > def []=(key,val) > @hsh[key]=val > end > > def <<(o) > @ary << o > end > > private > > def _dump(depth = -1) > Marshal.dump([@hsh,@ary,tainted?],depth) > end > > def self._load(str) > instance.instance_eval { > h,a,t = *Marshal.load(str) > @hsh.merge h > @ary.concat a > if t > taint > else > untaint > end > } > instance > end > > private_class_method :_load >end > > >/Christoph > > > > >