lib/observer.rb


DEFINITIONS

This source file includes following functions.


   1  # Observable Mixin
   2  # 
   3  # Observers must respond to update
   4  
   5  module Observable
   6    def add_observer(observer)
   7      @observer_peers = [] unless defined? @observer_peers
   8      unless observer.respond_to? :update
   9        raise NameError, "observer needs to respond to `update'" 
  10      end
  11      @observer_peers.push observer
  12    end
  13    def delete_observer(observer)
  14      @observer_peers.delete observer if defined? @observer_peers
  15    end
  16    def delete_observers
  17      @observer_peers.clear if defined? @observer_peers
  18    end
  19    def count_observers
  20      if defined? @observer_peers
  21        @observer_peers.size
  22      else
  23        0
  24      end
  25    end
  26    def changed(state=true)
  27      @observer_state = state
  28    end
  29    def changed?
  30      if defined? @observer_state and @observer_state
  31        true
  32      else
  33        false
  34      end
  35    end
  36    def notify_observers(*arg)
  37      if defined? @observer_state and @observer_state
  38        if defined? @observer_peers
  39          for i in @observer_peers.dup
  40            i.update(*arg)
  41          end
  42        end
  43        @observer_state = false
  44      end
  45    end
  46  end