Class: Kward::Steering

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/steering.rb

Overview

Thread-safe queue for in-flight user steering events.

Defined Under Namespace

Classes: Event

Instance Method Summary collapse

Constructor Details

#initialize(on_submit: nil) ⇒ Steering

Returns a new instance of Steering.



10
11
12
13
14
15
16
# File 'lib/kward/steering.rb', line 10

def initialize(on_submit: nil)
  @listeners = []
  @listeners << on_submit if on_submit
  @events = []
  @mutex = Mutex.new
  @condition = ConditionVariable.new
end

Instance Method Details

#on_submit(&block) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/kward/steering.rb', line 18

def on_submit(&block)
  return unless block

  @mutex.synchronize { @listeners << block }
  lambda do
    @mutex.synchronize { @listeners.delete(block) }
  end
end

#submit(input) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/kward/steering.rb', line 27

def submit(input)
  event = Event.new(input: input, created_at: Time.now.utc.iso8601(3))
  listeners = nil
  @mutex.synchronize do
    @events << event
    listeners = @listeners.dup
    @condition.broadcast
  end
  listeners.each { |listener| listener.call(event) }
  event
end

#wait(after: 0, timeout: nil) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/kward/steering.rb', line 39

def wait(after: 0, timeout: nil)
  deadline = timeout ? Time.now + timeout.to_f : nil
  @mutex.synchronize do
    loop do
      event = @events[after]
      return event if event

      if deadline
        remaining = deadline - Time.now
        return nil if remaining <= 0

        @condition.wait(@mutex, remaining)
      else
        @condition.wait(@mutex)
      end
    end
  end
end