Class: Proclib::OutputHandler::LineBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/proclib/output_handler.rb

Overview

Calls its given callback with each line in the input written to the buffer

Constant Summary collapse

NEWLINE =
"\n"
MAX_SIZE =
1024 * 10
SIZE_ERROR_MESSAGE =
"A line of greater than #{MAX_SIZE} bytes was " \
"encountered from a process."
MaxSizeExceeded =
Class.new(Error)

Instance Method Summary collapse

Constructor Details

#initialize(&blk) ⇒ LineBuffer

Returns a new instance of LineBuffer.



17
18
19
20
# File 'lib/proclib/output_handler.rb', line 17

def initialize(&blk)
  @buf = String.new
  @callback = blk
end

Instance Method Details

#flushObject



36
37
38
# File 'lib/proclib/output_handler.rb', line 36

def flush
  callback.call(buf + "\n") unless buf.empty?
end

#write(str) ⇒ Object



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

def write(str)
  buf << str

  while buf.include?(NEWLINE)
    idx = buf.index(NEWLINE)
    callback.call(buf[0..(idx - 1)] + NEWLINE)
    self.buf = (buf[(idx + 1)..-1] || String.new)
  end

  if buf.bytesize > MAX_SIZE
    raise MaxSizeExceeded, SIZE_ERROR_MESSAGE
  end
end