class ElasticTabstops::OutstreamToLines

Public Class Methods

new(liner) click to toggle source

INVARIANT: @text contains no newlines

# File lib/elastic_tabstops/outstream_to_lines.rb, line 6
def initialize(liner)
  @text = ''
  @liner = liner
end

Public Instance Methods

flush() click to toggle source
# File lib/elastic_tabstops/outstream_to_lines.rb, line 32
def flush
  @liner.line(@text) unless @text.empty?
  @liner.line('') # signals end-of-input to the @liner
end
print(*args) click to toggle source
puts(*args) click to toggle source
# File lib/elastic_tabstops/outstream_to_lines.rb, line 11
def puts(*args)
  sio = StringIO.new
  result = sio.puts(*args)
  add_text(sio.string)
  result
end
write(*args) click to toggle source
# File lib/elastic_tabstops/outstream_to_lines.rb, line 25
def write(*args)
  sio = StringIO.new
  result = sio.write(*args)
  add_text(sio.string)
  result
end

Private Instance Methods

add_text(text, flush: false) click to toggle source

Add text to @text. Move completed lines (at the beginning of @text) to @liner.

# File lib/elastic_tabstops/outstream_to_lines.rb, line 41
def add_text(text, flush: false)
  # ASSERTION: @text contains no newlines, due to class invariant
  @text += text

  # At this point, @text _may_ contain newlines, thus violating the class
  # invariant.  Move any full lines _out_ of @text and into @liner.
  pos = 0
  while (m = @text.match(/\G.*?\r?\n/, pos)) do
    @liner.line m[0]
    pos += m[0].size
  end
  @text = @text[pos..-1]

  # ASSERTION: @text contains no newlines; invariant has been restored
end