From: Michael Neumann Date: 2004-11-11T04:23:43+09:00 Subject: Re: automatically call function on attribute set On Thu, Nov 11, 2004 at 03:13:30AM +0900, Joe Laughlin wrote: > I have a class that represents an airplane. This class has a bunch of data > members: x/y/z positions, x/y/z velocities, pitches, rolls, etc. What I did > is let the user configure what different attributes the airplane had in a > YAML config file, then have the airplane class read in that file and setup > attr_accessors for each attribute in the file. > > I have another object (call it airplane_drawing) that is responsible for > drawing this airplane on the screen. It needs to have access to some of the > attributes of the airplane, and it needs have some of its own attributes > changed whenever airplane's attributes changes. > > What is the best way to get airplane_drawing to be notified whenever some > attribute of airplane is changed? Should I have a thread (or similar) that > checks the airplane object to see if anything's changed? You should use an Observer. require 'observer' class Airplane include Observable def initialize @x = 0 end def fly # airplane changes it's coordinate @x += 10 changed notify_observers(self) end end class AirplaneDrawing def update(obj) # ... end end airbus = Airplane.new drawing = AirplaneDrawing.new airbus.add_observer(drawing) airbus.fly Regards, Michael