From: Logan Capaldo Date: 2006-08-28T14:48:09+09:00 Subject: Re: Detecting when an object's instance variables are modifi On Aug 27, 2006, at 5:37 PM, Paul Murton wrote: > unknown wrote: >> Hi -- >> >> On Mon, 28 Aug 2006, David Vallner wrote: >> >>> monitor setters. Would probably be horribly, terribly slow. >>> >>> It's probably best to have your objects trace changes by design. >>> Modify the >>> Object class to have a #dirty? and #clean! method, and alias / >>> redefine the >>> #attr_writer method to generate methods that will set the dirty >>> flag when >>> used? >> >> I was thinking of something similar, but using Observable -- but the >> problem is that it would only work for instance variable changes that >> go through attr_writer. >> >> >> David > > I appreciate all of the help so far. I had considered the > possibility of > redefining attr_writer, but had hoped there might be a way of doing > this > so that it would work for changes that DON'T go through attr_writer. > > In fact this is actually quite important to me, because I am > interested > in changes to ANY instance variable (including if a previously > non-existant instance variable is set), not just those made externally > accessible with a writer method. I should have been more clear about > this in my original post. > > I've been thinking about this for ages now and my current thoughts are > that there may not be any way of getting quite what I want here :/ > > Any further suggestions appreciated > class A # all method definitions here ... instance_methods(false).each do |m| m_obj = instance_method(m) define_method(m) do |*args| before = instance_variables.inject({}) { |h,k| h[k] = instance_variable_get(k); h } res = m_obj.bind(self).call(*args) after = instance_variables.inject({}) { |h,k| h[k] = instance_variable_get(k); h } return res end end end Salt and season to taste. (Note that the granularity is at the method level, not per statement, I'm assuming that's acceptable enough). > -- > Posted via http://www.ruby-forum.com/. >