Class: IRuby::EventManager

Inherits:
Object
  • Object
show all
Defined in:
lib/iruby/event_manager.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(available_events) ⇒ EventManager

Returns a new instance of EventManager.



3
4
5
6
# File 'lib/iruby/event_manager.rb', line 3

def initialize(available_events)
  @available_events = available_events.dup.freeze
  @callbacks = available_events.map {|n| [n, []] }.to_h
end

Instance Attribute Details

#available_eventsObject (readonly)

Returns the value of attribute available_events.



8
9
10
# File 'lib/iruby/event_manager.rb', line 8

def available_events
  @available_events
end

Instance Method Details

#register(event, &block) ⇒ Object



10
11
12
13
14
# File 'lib/iruby/event_manager.rb', line 10

def register(event, &block)
  check_available_event(event)
  @callbacks[event] << block unless block.nil?
  block
end

#trigger(event, *args, **kwargs) ⇒ Object



26
27
28
29
30
31
# File 'lib/iruby/event_manager.rb', line 26

def trigger(event, *args, **kwargs)
  check_available_event(event)
  @callbacks[event].each do |fn|
    fn.call(*args, **kwargs)
  end
end

#unregister(event, callback) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/iruby/event_manager.rb', line 16

def unregister(event, callback)
  check_available_event(event)
  val = @callbacks[event].delete(callback)
  unless val
    raise ArgumentError,
          "Given callable object #{callback} is not registered as a #{event} callback"
  end
  val
end