Class: NonblockingIOWrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/bel/nonblocking_io_wrapper.rb

Overview

Provides a platform-independent, non-blocking wrapper for reading an IO-like object. This wrapper object must be enumerated using the #each method.

Instance Method Summary collapse

Constructor Details

#initialize(io, read_length = (128 * 1024)) ⇒ NonblockingIOWrapper

Initialize this wrapper around the io object and read at most read_length bytes in a non-blocking manner.

Parameters:

  • io (IO)

    an IO-like object

  • read_length (Fixnum) (defaults to: (128 * 1024))

    the buffer length to read



11
12
13
14
15
# File 'lib/bel/nonblocking_io_wrapper.rb', line 11

def initialize(io, read_length = (128 * 1024))
  @io          = io
  @read_length = read_length
  @read_method = nonblocking_read(@io)
end

Instance Method Details

#each {|buffer| ... } ⇒ Object

Yields each buffer read from the wrapped IO-like object to the provided block (e.g. { |block| … }). The read length is set on #initialize.

Yields:

  • the buffers read from the IO-like object

Yield Parameters:

  • buffer (String)

    the read buffer as uninterpreted bytes



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/bel/nonblocking_io_wrapper.rb', line 22

def each
  begin
    while buffer = @read_method.call(@read_length)
      yield buffer
    end
  rescue IO::WaitReadable
    IO.select([@io])
    retry
  rescue EOFError
    # end of stream; parsing complete
  end
end