Module: Observable
- Defined in:
- lib/observer.rb
Overview
Implements the Observable design pattern as a mixin so that other objects can be notified of changes in state. See observer.rb for details and an example.
Instance Method Summary collapse
-
#add_observer(observer) ⇒ Object
Add
observer
as an observer on this object. -
#changed(state = true) ⇒ Object
Set the changed state of this object.
-
#changed? ⇒ Boolean
Query the changed state of this object.
-
#count_observers ⇒ Object
Return the number of observers associated with this object.
-
#delete_observer(observer) ⇒ Object
Delete
observer
as an observer on this object. -
#delete_observers ⇒ Object
Delete all observers associated with this object.
-
#notify_observers(*arg) ⇒ Object
If this object's changed state is
true
, invoke the update method in each currently associated observer in turn, passing it the given arguments.
Instance Method Details
#add_observer(observer) ⇒ Object
Add observer
as an observer on this object. observer
will now receive notifications.
123 124 125 126 127 128 129 |
# File 'lib/observer.rb', line 123 def add_observer(observer) @observer_peers = [] unless defined? @observer_peers unless observer.respond_to? :update raise NoMethodError, "observer needs to respond to `update'" end @observer_peers.push observer end |
#changed(state = true) ⇒ Object
Set the changed state of this object. Notifications will be sent only if the changed state
is true
.
161 162 163 |
# File 'lib/observer.rb', line 161 def changed(state=true) @observer_state = state end |
#changed? ⇒ Boolean
Query the changed state of this object.
168 169 170 171 172 173 174 |
# File 'lib/observer.rb', line 168 def changed? if defined? @observer_state and @observer_state true else false end end |
#count_observers ⇒ Object
Return the number of observers associated with this object.
149 150 151 152 153 154 155 |
# File 'lib/observer.rb', line 149 def count_observers if defined? @observer_peers @observer_peers.size else 0 end end |
#delete_observer(observer) ⇒ Object
Delete observer
as an observer on this object. It will no longer receive notifications.
135 136 137 |
# File 'lib/observer.rb', line 135 def delete_observer(observer) @observer_peers.delete observer if defined? @observer_peers end |
#delete_observers ⇒ Object
Delete all observers associated with this object.
142 143 144 |
# File 'lib/observer.rb', line 142 def delete_observers @observer_peers.clear if defined? @observer_peers end |
#notify_observers(*arg) ⇒ Object
If this object's changed state is true
, invoke the update method in each currently associated observer in turn, passing it the given arguments. The changed state is then set to false
.
181 182 183 184 185 186 187 188 189 190 |
# File 'lib/observer.rb', line 181 def notify_observers(*arg) if defined? @observer_state and @observer_state if defined? @observer_peers for i in @observer_peers.dup i.update(*arg) end end @observer_state = false end end |