Class: Orator::EventHandler
- Inherits:
-
Object
- Object
- Orator::EventHandler
- Defined in:
- lib/orator/event_handler.rb
Overview
This handles events and calls the callbacks for them.
Instance Method Summary collapse
-
#events(matching = nil) ⇒ Set<Hash>
Accessor for events.
-
#initialize(&block) ⇒ void
constructor
Initialize the event handler.
-
#on(event, klass = nil, count = nil, &block) ⇒ void
This adds an event to the set.
-
#trigger(event, context, *args) ⇒ Object?
This triggers the events.
Constructor Details
#initialize(&block) ⇒ void
Initialize the event handler.
10 11 12 13 14 |
# File 'lib/orator/event_handler.rb', line 10 def initialize(&block) @events = [] @_number = 0 instance_exec &block if block_given? end |
Instance Method Details
#events(matching = nil) ⇒ Set<Hash>
Accessor for events. If the first parameter is passed, it checks for events that match that event.
76 77 78 79 80 81 82 |
# File 'lib/orator/event_handler.rb', line 76 def events(matching = nil) if matching @events.select { |e| e[:event] == matching.to_s } else @events.dup end end |
#on(event, klass = nil, count = nil, &block) ⇒ void
This method returns an undefined value.
This adds an event to the set. It can accept a block or a class. If it’s a class, the class should inherit from [Base]. If both a class and a block is given, the block is preferred.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/orator/event_handler.rb', line 27 def on(event, klass = nil, count = nil, &block) puts "Binding #{event} to #{klass || block}..." if Orator.debug data = { :event => event.to_s, :count => count } if block_given? data[:block] = block elsif klass and klass < Base data[:class] = klass else raise ArgumentError, "No class or block was given." end @events << data unless @events.include?(data) end |
#trigger(event, context, *args) ⇒ Object?
This triggers the events. The events aren’t triggered in any particular order, since they are stored in a [Set]. Extra arguments are passed to the block/class. If no events are found, it runs the ‘socket.missing` event.
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/orator/event_handler.rb', line 52 def trigger(event, context, *args) puts "Running event #{event}..." if Orator.debug matching_events = events(event) if matching_events.length == 0 puts "Could not find event, running socket.missing..." if Orator.debug matching_events = events('socket.missing') end matching_events.map do |event| puts "Found responder #{event[:block] || event[:class]}" if Orator.debug run_event(event, context, args) if event[:count] then event[:count] -= 1 end end clear_events end |