Class: Kward::Steering

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

Defined Under Namespace

Classes: Event

Instance Method Summary collapse

Constructor Details

#initialize(on_submit: nil) ⇒ Steering

Returns a new instance of Steering.



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

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



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

def on_submit(&block)
  return unless block

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

#submit(input) ⇒ Object



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

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



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

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