Module: ContextR::EventMachine::ClassMethods

Includes:
UniqueId
Included in:
ContextR::EventMachine
Defined in:
lib/contextr/event_machine.rb

Instance Method Summary collapse

Methods included from UniqueId

#last_unique_id, #new_unique_id

Instance Method Details

#check_options_hash(options) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/contextr/event_machine.rb', line 28

def check_options_hash(options)
  observed = {}
  observed[:event] = options[:on_event]
  observed[:module] = options[:in_class] || options[:in_module]
  [:event, :module].each do |key|
    unless observed[key]
      raise ArgumentError.new("Missing Argument in options Hash")
    end
  end
  unless self.listeners.keys.include?(observed[:event])
    raise ArgumentError.new("Unknown event `#{observed[:event]}`. " + 
            "Please use one of these: #{self.listeners.keys.join(', ')}")
  end
  observed
end

#listenersObject



6
7
8
# File 'lib/contextr/event_machine.rb', line 6

def listeners 
  @listeners ||= {:method_added => {}}
end

#observe_method_added(modul) ⇒ Object



54
55
56
# File 'lib/contextr/event_machine.rb', line 54

def observe_method_added(modul)
  modul.extend(ContextRListener)
end

#on_method_added(modul, name) ⇒ Object



21
22
23
24
25
26
# File 'lib/contextr/event_machine.rb', line 21

def on_method_added(modul, name)
  version = self.new_unique_id
  self.listeners[:method_added][modul].to_a.each do |listener, method|
    listener.send(method, modul, name, version)
  end 
end

#register(listener, callback, options) ⇒ Object



10
11
12
13
14
# File 'lib/contextr/event_machine.rb', line 10

def register(listener, callback, options)
  observed = check_options_hash(options)
  register_observers_on_demand(observed)
  self.listeners[observed[:event]][observed[:module]][listener] = callback
end

#register_observers_on_demand(observed) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/contextr/event_machine.rb', line 44

def register_observers_on_demand(observed)
  unless self.listeners[observed[:event]].include?(observed[:module])
    self.listeners[observed[:event]][observed[:module]] = {}
    case observed[:event]
    when :method_added
      observe_method_added(observed[:module])
    end
  end
end

#unregister(listener, *cumulated_options) ⇒ Object



16
17
18
19
# File 'lib/contextr/event_machine.rb', line 16

def unregister(listener, *cumulated_options)
  observed = check_options_hash(cumulated_options.last)
  self.listeners[observed[:event]][observed[:module]].delete(listener)
end