Module: BackgroundProcess::IOHelpers

Extended by:
IOHelpers
Included in:
IOHelpers
Defined in:
lib/background_process/io_helpers.rb

Instance Method Summary collapse

Instance Method Details

#detect(streams = [], timeout = nil, &block) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/background_process/io_helpers.rb', line 3

def detect(streams = [], timeout = nil, &block)
  begin
    Timeout::timeout(timeout) do
      # Something that should be interrupted if it takes too much time...
      until streams.empty?
        active_streams, _, _ = Kernel.select(streams, nil, nil, 1)
        active_streams.each do |s|
          (streams -= [s]; next) if s.eof?
          content = s.gets
          if result = (block.arity == 1 ? yield(content) : yield(s, content))
            return result
          end
        end if active_streams
      end
    end
    nil
  rescue Timeout::Error
    nil
  end

end