From: Anders Borch Date: 2003-07-03T18:08:25+09:00 Subject: Re: Auto-serialization (as in Vapor, sql-serialize, etc.): detecting changes to instance variables I haven't come up with a good solution to this myself, I'm merely suggesting, that maybe you are going about this the wrong way. I once read that if you are experiencing extreme difficulty with the implementation you are attempting then maybe you are attempting the wrong implementation. Very often there is an easy solution to an otherwise hard problem. Andrey Kulinich wrote: > Anders Borch wrote: > >> I think you should not allow anyone to modify your instance variables >> without going through your accessor methods. It ruins everything that >> encapsulation gives you. > > > Sometimes you can't control modification. > > class Session > attr_accessor :modified > def initialize > @data = {} > @modified = false > end > > def []( key ) # this may not ALWAYS be appropriate, but if you are # concerned with encapsulation you may want to consider it... d = @data[key].dup d.freeze return d > @data[key] > end > > def []=( key, value ) > @data[key] = value > @modified = true > end > end > > session = Session.new > session[:arr] = [] > session.modified # true. all ok > session.modified = false > > session[:arr].push( 1 ) > session.modified # false :( > >> Using the method_missing to test if the object has changed after each >> method call *could* solve your problem. > > > There is a trouble with method_missing: you can't redirect methods > 'to_s', '==' and other Object's methods, because they are defined in > Wrapper. > then overload ==, to_s and the rest of Object's methods to make sure they are passed on to the wrapped object. while freezing the return value of [] may not be a good idea, overloading the rest of Object's methods is certainly a nice and easy solution to most of your problems. /Anders -- dc -e 4dd*od3*dddn1-89danrn10-dan3+ann6*dan*2*an13dn1+dn2-dn3+5*ddan2/9+an13nap