Module: Tailor::CompositeObservable

Included in:
Lexer
Defined in:
lib/tailor/composite_observable.rb

Overview

Used by Lexer to provide publishing methods for observers. Any Ruler that wants to subscribe to Lexer events must use the methods defined here.

Class Method Summary collapse

Class Method Details

.define_observer(name) ⇒ Object

Defines three instance methods that provide for observing a Lexer object. If name was passed “test”:

  • #add_test_observer

  • #test_update

  • #notify_test_observers

Parameters:

  • name (String)

    The name of event to observe/subscribe to.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/tailor/composite_observable.rb', line 16

def self.define_observer(name)
  define_method("add_#{name}_observer") do |observer|
    @notifiers = {} unless defined? @notifiers
    @notifiers[name] = {} unless @notifiers[name]

    call_back = "#{name}_update".to_sym

    unless observer.respond_to? call_back
      raise NoMethodError,
        "observer '#{observer}' does not respond to '#{call_back}'"
    end

    @notifiers[name][observer] = call_back
  end

  define_method("notify_#{name}_observers") do |*args|
    if defined? @notifier_state and @notifier_state
      if @notifier_state[name]
        if defined? @notifiers and @notifiers[name]
          @notifiers[name].each do |k, v|
            k.send(v, *args)
          end
        end
      end
    end
  end

  define_method("#{name}_changed") do
    @notifier_state = {} unless defined? @notifier_state
    @notifier_state[name] = true
  end
end