Class: MainLoop::Bus

Inherits:
Object
  • Object
show all
Includes:
MonitorMixin
Defined in:
lib/main_loop/bus.rb

Constant Summary collapse

EOL =
"\n".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBus

Returns a new instance of Bus.



13
14
15
16
17
18
19
# File 'lib/main_loop/bus.rb', line 13

def initialize
  super()
  @read, @write = IO.pipe
  @read.sync = true
  @write.sync = true
  @buffer = ''
end

Instance Attribute Details

#readObject (readonly)

Returns the value of attribute read.



9
10
11
# File 'lib/main_loop/bus.rb', line 9

def read
  @read
end

#writeObject (readonly)

Returns the value of attribute write.



9
10
11
# File 'lib/main_loop/bus.rb', line 9

def write
  @write
end

Instance Method Details

#closeObject



25
26
27
28
# File 'lib/main_loop/bus.rb', line 25

def close
  @write.close rescue nil
  @read.close rescue nil
end

#closed?Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/main_loop/bus.rb', line 30

def closed?
  @write.closed? || @read.closed?
end

#empty?(timeout = 0) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/main_loop/bus.rb', line 21

def empty?(timeout = 0)
  !wait_for_event(timeout)
end

#gets(timeout) ⇒ Object



44
45
46
47
48
49
# File 'lib/main_loop/bus.rb', line 44

def gets(timeout)
  Timeouter.loop(timeout) do |t|
    line = gets_nonblock if wait_for_event(t.left)
    return line if line
  end
end

#gets_nonblockObject



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/main_loop/bus.rb', line 51

def gets_nonblock
  while (ch = @read.read_nonblock(1))
    @buffer << ch
    next if ch != MainLoop::Bus::EOL

    line = @buffer
    @buffer = ''
    return line&.strip
  end
  nil
rescue IO::WaitReadable
  nil
end

#puts(str) ⇒ Object



34
35
36
37
38
# File 'lib/main_loop/bus.rb', line 34

def puts(str)
  synchronize do
    @write.puts str.to_s
  end
end

#wait_for_event(timeout) ⇒ Object



40
41
42
# File 'lib/main_loop/bus.rb', line 40

def wait_for_event(timeout)
  IO.select([@read], [], [], timeout)
end