class Vx::Common::OutputBuffer

Attributes

interval[R]

Public Class Methods

new(interval = 1, &block) click to toggle source
# File lib/vx/common/output_buffer.rb, line 9
def initialize(interval = 1, &block)
  @interval = interval.to_f
  @buffer   = ""
  @write    = block
  @mutex    = Mutex.new
  @closed   = false

  start_watching
end

Public Instance Methods

<<(str) click to toggle source
# File lib/vx/common/output_buffer.rb, line 19
def << (str)
  closed!

  @mutex.synchronize do
    @buffer << str
  end
end
close() click to toggle source
# File lib/vx/common/output_buffer.rb, line 27
def close
  @closed = true
  @thread.join
end
empty?() click to toggle source
# File lib/vx/common/output_buffer.rb, line 37
def empty?
  @buffer.size == 0
end
flush() click to toggle source
# File lib/vx/common/output_buffer.rb, line 32
def flush
  closed!
  @mutex.synchronize { write }
end

Private Instance Methods

closed!() click to toggle source
# File lib/vx/common/output_buffer.rb, line 52
def closed!
  raise ClosedBuffer if @closed
end
start_watching() click to toggle source
# File lib/vx/common/output_buffer.rb, line 56
def start_watching
  @thread = Thread.new do
    loop do
      sleep interval

      unless empty?
        @mutex.synchronize { write }
      end

      break if @closed
    end
  end
  @thread.abort_on_exception = true
end
write() click to toggle source
# File lib/vx/common/output_buffer.rb, line 45
def write
  unless empty?
    @write.call @buffer.dup
    @buffer.clear
  end
end