Class: Rubsh::StreamReader

Inherits:
Object
  • Object
show all
Defined in:
lib/rubsh/stream_reader.rb

Constant Summary collapse

BUFSIZE =
16 * 1024

Instance Method Summary collapse

Constructor Details

#initialize(rd, bufsize: nil, &block) ⇒ StreamReader

Returns a new instance of StreamReader.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rubsh/stream_reader.rb', line 5

def initialize(rd, bufsize: nil, &block)
  @thr = ::Thread.new do
    if ::Thread.current.respond_to?(:report_on_exception)
      ::Thread.current.report_on_exception = false
    end

    readers = [rd]
    while readers.any?
      ready = ::IO.select(readers, nil, readers)
      ready[0].each do |reader|
        if bufsize.nil?
          chunk = reader.readpartial(BUFSIZE)
        elsif bufsize == 0
          chunk = reader.readline
        else
          chunk = reader.read(bufsize)
          raise ::EOFError if chunk.nil?
        end

        chunk.force_encoding(::Encoding.default_external)
        block.call(chunk)
      rescue ::EOFError, ::Errno::EPIPE, ::Errno::EIO
        readers.delete(reader)
        reader.close
      end
    end
  end
end

Instance Method Details

#waitvoid

This method returns an undefined value.



35
36
37
# File 'lib/rubsh/stream_reader.rb', line 35

def wait
  @thr.join
end