Class: IRC::EventQueue

Inherits:
Object
  • Object
show all
Defined in:
lib/rhuidean/event.rb

Overview

A queue of events, with handlers. One per object.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeEventQueue

Create a new EventQueue.


returns

self



36
37
38
39
# File 'lib/rhuidean/event.rb', line 36

def initialize
    @queue    = []
    @handlers = {}
end

Instance Attribute Details

#handlersObject (readonly)

Returns the value of attribute handlers.



29
30
31
# File 'lib/rhuidean/event.rb', line 29

def handlers
  @handlers
end

#queueObject (readonly)

Returns the value of attribute queue.



29
30
31
# File 'lib/rhuidean/event.rb', line 29

def queue
  @queue
end

Instance Method Details

#handle(event, &block) ⇒ Object

Register a handler for an event.


event

event name as a Symbol

block

block to call to handle event

returns

self



69
70
71
72
73
# File 'lib/rhuidean/event.rb', line 69

def handle(event, &block)
    (@handlers[event] ||= []) << block

    self
end

#needs_ran?Boolean

Does the event queue have anything in it?


returns

true or false

Returns:

  • (Boolean)


80
81
82
# File 'lib/rhuidean/event.rb', line 80

def needs_ran?
    @queue.empty? ? false : true
end

#post(event, *args) ⇒ Object

Post a new event to the queue to be handled. Events can be posted more than once per loop, so the callers need to make sure calling the same handlers twice for the same run isn’t going to bork something serious like make an otherwise good call become blocking (like read).


event

event name as a Symbol

args

list of arguments to pass to handler

returns

self



57
58
59
60
# File 'lib/rhuidean/event.rb', line 57

def post(event, *args)
    @queue << Event.new(event, *args)
    self
end

#runObject

Goes through the event queue and runs the handlers.


returns

self



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/rhuidean/event.rb', line 89

def run
    needs_exit = false

    while e = @queue.shift
        next unless @handlers[e.event]

        # If there's an :exit event in the queue wait until we're
        # all the way done before we handle it.
        if e.event == :exit
            needs_exit = e
            next
        end

        @handlers[e.event].each { |block| block.call(*e.args) }
    end

    # Now we can exit... any events that got added by handling routines
    # just don't happen. This is arguably a bug.
    @handlers[:exit].each { |b| b.call(*needs_exit.args) } if needs_exit

    self
end