From: "Jesús Gabriel y Galán" Date: 2011-10-20T23:51:29+09:00 Subject: Re: Call method on attribute update On Thu, Oct 20, 2011 at 8:01 AM, Gary Wright wrote: > > On Oct 20, 2011, at 1:38 AM, Jason Lillywhite wrote: >> If @yn is updated, automatically run method "foo.calcArea". The way I >> have it now requires me to do: >> >> foo.yn = 100.0 >> foo.calcArea >> >> There must be a way to let ruby call that method for me. > > > Just define the attribute writer method yourself instead of using the helpers: > > class Foo >  attr_reader :yn >  def yn=(value) >    @yn = value >    calcArea >  end > >  def calcArea >     puts "recomputing area" >  end > end > >>> f = Foo.new      #=> # >>> f.yn = 100       #=> 100 > recomputing area >>> f.yn             #=> 100 > > > Gary Wright > > > If you find yourself doing that a lot, you could create a little utility: class Class def attr_writer_with_callbacks attr, *callbacks instance_eval do define_method("#{attr}=") do |value| instance_variable_set "@#{attr}", value callbacks.each {|callback| send callback} end end end end ruby-1.8.7-p334 :038 > class A ruby-1.8.7-p334 :039?> attr_writer_with_callbacks :test, :updated, :modified ruby-1.8.7-p334 :040?> def updated ruby-1.8.7-p334 :041?> puts "updated" ruby-1.8.7-p334 :042?> end ruby-1.8.7-p334 :043?> def modified ruby-1.8.7-p334 :044?> puts "also modified" ruby-1.8.7-p334 :045?> end ruby-1.8.7-p334 :046?> end => nil ruby-1.8.7-p334 :047 > A.new.test = "value" updated also modified => "value" Jesus.