class Tracksperanto::BufferIO

BufferIO is used for writing big segments of text. It works like a StringIO, but when the size of the underlying string buffer exceeds MAX_IN_MEM_BYTES the string will be flushed to disk and it automagically becomes a Tempfile

Constants

MAX_IN_MEM_BYTES

Public Class Methods

new() click to toggle source
# File lib/tracksperanto/buffer_io.rb, line 18
def initialize
  @backing_buffer = StringIO.new
end

Public Instance Methods

<<(s)
Alias for: write
close!() click to toggle source
# File lib/tracksperanto/buffer_io.rb, line 35
def close!
  @backing_buffer.close! if @tempfile_in
  @backing_buffer = nil
end
file_backed?() click to toggle source

Tells whether this one is on disk

# File lib/tracksperanto/buffer_io.rb, line 49
def file_backed?
  @tempfile_in
end
putc(c) click to toggle source
Calls superclass method
# File lib/tracksperanto/buffer_io.rb, line 31
def putc(c)
  super.tap { replace_with_tempfile_if_needed }
end
puts(s) click to toggle source
Calls superclass method
# File lib/tracksperanto/buffer_io.rb, line 27
def puts(s)
  super.tap { replace_with_tempfile_if_needed }
end
to_file() click to toggle source

Sometimes you just need to upgrade to a File forcibly (for example if you want) to have an object with many iterators sitting on it. We also flush here.

# File lib/tracksperanto/buffer_io.rb, line 42
def to_file
  replace_with_tempfile unless @tempfile_in
  flush
  self
end
write(s) click to toggle source
Calls superclass method
# File lib/tracksperanto/buffer_io.rb, line 22
def write(s)
  super.tap { replace_with_tempfile_if_needed }
end
Also aliased as: <<

Private Instance Methods

replace_with_tempfile() click to toggle source
# File lib/tracksperanto/buffer_io.rb, line 55
def replace_with_tempfile
  sio = @backing_buffer
  tf = Tempfile.new("tracksperanto-xbuf")
  tf.set_encoding(Encoding::BINARY) if @rewindable_io.respond_to?(:set_encoding)
  tf.binmode
  tf.write(sio.string)
  tf.flush # Needed if we are going to reopen this file soon from another thread/loop
  sio.string = ""
  GC.start
  @backing_buffer = tf
  
  @tempfile_in = true
end
replace_with_tempfile_if_needed() click to toggle source
# File lib/tracksperanto/buffer_io.rb, line 69
def replace_with_tempfile_if_needed
  replace_with_tempfile if !@tempfile_in && pos > MAX_IN_MEM_BYTES
end