Class: PrettyPrint::Buffer::ArrayBuffer

Inherits:
DefaultBuffer show all
Defined in:
lib/syntax_tree/prettyprint.rb

Overview

This is an output buffer that wraps an array output object. It provides a trim! method that trims off trailing whitespace from the last element in the array if it’s an unfrozen string using the same method as the StringBuffer.

Instance Attribute Summary

Attributes inherited from DefaultBuffer

#output

Instance Method Summary collapse

Methods inherited from DefaultBuffer

#<<

Constructor Details

#initialize(output = []) ⇒ ArrayBuffer

Returns a new instance of ArrayBuffer.



310
311
312
# File 'lib/syntax_tree/prettyprint.rb', line 310

def initialize(output = [])
  super(output)
end

Instance Method Details

#trim!Object



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/syntax_tree/prettyprint.rb', line 314

def trim!
  return 0 if output.empty?

  trimmed = 0

  while output.any? && output.last.is_a?(String) &&
          output.last.match?(/\A[\t ]*\z/)
    trimmed += output.pop.length
  end

  if output.any? && output.last.is_a?(String) && !output.last.frozen?
    length = output.last.length
    output.last.gsub!(/[\t ]*\z/, "")
    trimmed += length - output.last.length
  end

  trimmed
end