Module: Observatory::Observer

Defined in:
lib/observatory/observer.rb

Overview

TODO:

allow registering a single method to mulitple signals, or even matching by regular expression…?

TODO:

this is pretty magicky. Might need to refactor to make things more explicit and obvious.

Note:

Including the Observer module in your object will override your initializer.

The Observer module enhances your classes with some simple syntactic sugar to register methods as observers. You may very well register your methods manually, but these methods may increase your code readability.

This module will override your ‘initialize` method to automatically register all observer methods with the dispatcher. In order to do so, it will alias your own `initialize` method and create a new one that both calls the old initializer and registers observers. This does mean that your initializer needs to set up a dispatcher object, probably via constructor dependency injection.

The main benefit of using this module in your classes is you get the class macro ‘observe` which will set up the next method that is declared in the class as an observer for the given signal name.

Examples:

Registering a method as an observer for a signal

class Logger
  include Observatory::Observer

  def initialize(dispatcher)
    @dispatcher = dispatcher
  end

  observe 'post.publish'
  def log(event)
    puts "Event #{event.signal} happened at #{Time.now}"
  end
end

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/observatory/observer.rb', line 39

def self.included(base)
  base.extend ClassMethods
  base.overwrite_initialize
  base.class_eval do
    attr_reader :dispatcher
  end

  base.instance_eval do
    def method_added(name)
      if name == :initialize
        overwrite_initialize
      else
        if @observer_next_event_name_to_observe
          @observers_to_set_up ||= {}
          @observers_to_set_up[@observer_next_event_name_to_observe] ||= []
          @observers_to_set_up[@observer_next_event_name_to_observe] << name
          @observer_next_event_name_to_observe = nil
        end
      end
    end
  end
end