On 11/19/06, Jeremy Henty <jeremy / chaos.org.uk> wrote: > I'm developing an editing application with full undo/redo, so my > objects must log all changes to a history that can be rolled backwards > and forwards. This is just crying out for some fancy metaprogramming, > and it would be really neat if I could insert some code that is called > whenever an object assigns an instance variable. Is there anything > like that? > > Regards, > > Jeremy Henty I'm not aware of any hooks for instance variables, but as long as you're setting everything using setter methods or attr_accessor you can just hook into all methods ending in a "=". class A attr_accessor :a, :b instance_methods(false).each{|m| alias_method "orig_#{m}",m define_method(m){|*args| puts "called #{m}" send("orig_#{m}",*args) } if m[-1] == ?= } end o = A.new o.a=[4, 8, 15, 16, 23] # => called a= o.b=42 # => called b= puts o.b # just 42, without any "called b"