1998-01-16 07:13:05 -05:00
|
|
|
# Observable Mixin
|
|
|
|
#
|
|
|
|
# Observers must respond to update
|
|
|
|
|
|
|
|
module Observable
|
|
|
|
def add_observer(observer)
|
2000-04-10 01:48:43 -04:00
|
|
|
@observer_peers = [] unless defined? @observer_peers
|
2001-02-02 06:38:20 -05:00
|
|
|
unless observer.respond_to? :update
|
2002-11-14 17:46:00 -05:00
|
|
|
raise NoMethodError, "observer needs to respond to `update'"
|
1998-01-16 07:13:05 -05:00
|
|
|
end
|
|
|
|
@observer_peers.push observer
|
|
|
|
end
|
|
|
|
def delete_observer(observer)
|
2000-04-10 01:48:43 -04:00
|
|
|
@observer_peers.delete observer if defined? @observer_peers
|
1998-01-16 07:13:05 -05:00
|
|
|
end
|
|
|
|
def delete_observers
|
2000-04-10 01:48:43 -04:00
|
|
|
@observer_peers.clear if defined? @observer_peers
|
1998-01-16 07:13:05 -05:00
|
|
|
end
|
|
|
|
def count_observers
|
2000-04-10 01:48:43 -04:00
|
|
|
if defined? @observer_peers
|
1998-01-16 07:13:05 -05:00
|
|
|
@observer_peers.size
|
|
|
|
else
|
|
|
|
0
|
|
|
|
end
|
|
|
|
end
|
1999-08-13 01:45:20 -04:00
|
|
|
def changed(state=true)
|
1998-01-16 07:13:05 -05:00
|
|
|
@observer_state = state
|
|
|
|
end
|
|
|
|
def changed?
|
2000-04-10 01:48:43 -04:00
|
|
|
if defined? @observer_state and @observer_state
|
|
|
|
true
|
|
|
|
else
|
|
|
|
false
|
|
|
|
end
|
1998-01-16 07:13:05 -05:00
|
|
|
end
|
|
|
|
def notify_observers(*arg)
|
2000-04-10 01:48:43 -04:00
|
|
|
if defined? @observer_state and @observer_state
|
|
|
|
if defined? @observer_peers
|
2000-01-31 22:12:21 -05:00
|
|
|
for i in @observer_peers.dup
|
1999-01-19 23:59:39 -05:00
|
|
|
i.update(*arg)
|
|
|
|
end
|
1998-01-16 07:13:05 -05:00
|
|
|
end
|
1999-08-13 01:45:20 -04:00
|
|
|
@observer_state = false
|
1998-01-16 07:13:05 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|