Class: Rubevent::EventLoop

Inherits:
Object
  • Object
show all
Defined in:
lib/rubevent/event_loop.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ EventLoop

Returns a new instance of EventLoop.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/rubevent/event_loop.rb', line 11

def initialize(opts = {})
  @active = false
  @events = []
  @listeners = {}
  @metrics = Metrics.new

  configure opts

  @loop = Thread.new do
    loop do
      if @events.empty? || @halted
        Thread.stop
      else
        run
      end
    end
  end
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



8
9
10
# File 'lib/rubevent/event_loop.rb', line 8

def config
  @config
end

#metricsObject (readonly)

Returns the value of attribute metrics.



9
10
11
# File 'lib/rubevent/event_loop.rb', line 9

def metrics
  @metrics
end

Instance Method Details

#listen(event_type) ⇒ Object



37
38
39
40
41
42
# File 'lib/rubevent/event_loop.rb', line 37

def listen event_type
  check_max_listeners
  listener = Proc.new # wrap the passed block in a proc
  listeners_for(event_type).push listener
  @metrics.registered event_type
end

#publish(event, details = {}) ⇒ Object



30
31
32
33
34
35
# File 'lib/rubevent/event_loop.rb', line 30

def publish(event, details = {})
  check_max_queue_size
  @events.push [event, details] # array simulates pair
  @metrics.received event
  start unless @halted
end

#runObject



54
55
56
57
58
59
# File 'lib/rubevent/event_loop.rb', line 54

def run
  return if @events.empty? || @halted
  event_type, details = @events.shift
  @metrics.mark_processed event_type
  listeners_for(event_type).each { |listener| listener.call details }
end

#startObject



44
45
46
47
48
# File 'lib/rubevent/event_loop.rb', line 44

def start
  @halted = false
  @loop.wakeup
  self
end

#stopObject



50
51
52
# File 'lib/rubevent/event_loop.rb', line 50

def stop
  @halted = true
end