Module: Copland::EventProducer

Included in:
Registry
Defined in:
lib/copland/event-producer.rb

Overview

Any service implementation that wishes to be able to alert other services of events may mixin this module. If it does not, it may still be used as an event producer as long as it implements:

# The #add_listener method # A notification method that invokes some listener method on each listener,

which method must be called "on_#{event_name}" and must accept the
producer as the first argument.

Instance Method Summary collapse

Instance Method Details

#add_listener(listener) ⇒ Object

Add the given listener to this producer’s list of listeners. A listener may be added multiple times.



48
49
50
51
# File 'lib/copland/event-producer.rb', line 48

def add_listener( listener )
  ( @listeners ||= [] ).push listener
  self
end

#each_listenerObject

Iterates over each listener in the list. It first makes a copy of the list and then iterates over the copy, so it essentially iterates over a snapshot of the listener list. This makes its behavior deterministic when dealing with multiple threads of control.



65
66
67
68
69
70
71
# File 'lib/copland/event-producer.rb', line 65

def each_listener
  return unless @listeners
  @listeners.dup.each do |listener|
    yield listener
  end
  self
end

#fire_event(event, *args) ⇒ Object

Signals the listeners that some event has occurred. The event method should be either a String or a Symbol. Each listener is then queried to see if they respond to a method called “on_#event”, and if they do, they are sent that message, along with the producer and the argument list. If they don’t respond to “on_#event”, they are then asked if they respond to “on_any_event”, if they do, they are sent that message, along with the producer, the event, and the argument list.



80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/copland/event-producer.rb', line 80

def fire_event( event, *args )
  method = "on_#{event.to_s}"
  general_method = "on_any_event"
  each_listener do |listener|
    if listener.respond_to?( method )
      listener.__send__( method, self, *args )
    elsif listener.respond_to?( general_method )
      listener.__send__( general_method, self, event, *args )
    end
  end
  self
end

#remove_listener(listener) ⇒ Object

Remove the given listener from the producer’s list of listeners. If the listener does not exist in the listener list, nothing happens. If it exists more than once, only the first instance is removed.



56
57
58
59
# File 'lib/copland/event-producer.rb', line 56

def remove_listener( listener )
  @listeners.delete listener if @listeners
  self
end