Sha256: 26027f69ab92b4d3b4e437d01fb78de64e7ce22a7d3904ce9c23117dbead940f

Contents?: true

Size: 1.21 KB

Versions: 16

Compression:

Stored size: 1.21 KB

Contents

require 'thread'

module Vx
  module Common
    class OutputBuffer

      attr_reader :interval

      def initialize(interval = 1, &block)
        @interval = interval.to_f
        @buffer   = ""
        @write    = block
        @mutex    = Mutex.new
        @closed   = false

        start_watching
      end

      def << (str)
        closed!

        @mutex.synchronize do
          @buffer << str
        end
      end

      def close
        @closed = true
        @thread.join
      end

      def flush
        closed!
        @mutex.synchronize { write }
      end

      def empty?
        @buffer.size == 0
      end

      class ClosedBuffer < Exception ; end

      private

        def write
          unless empty?
            @write.call @buffer.dup
            @buffer.clear
          end
        end

        def closed!
          raise ClosedBuffer if @closed
        end

        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

    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
vx-common-0.4.0 lib/vx/common/output_buffer.rb
vx-common-0.3.2 lib/vx/common/output_buffer.rb
vx-common-0.3.1 lib/vx/common/output_buffer.rb
vx-common-0.3.0 lib/vx/common/output_buffer.rb
vx-common-0.2.1 lib/vx/common/output_buffer.rb
vx-common-0.2.0.pre38 lib/vx/common/output_buffer.rb
vx-common-0.2.0.pre37 lib/vx/common/output_buffer.rb
vx-common-0.2.0.pre36 lib/vx/common/output_buffer.rb
vx-common-0.2.0.pre35 lib/vx/common/output_buffer.rb
vx-common-0.2.0.pre34 lib/vx/common/output_buffer.rb
vx-common-0.2.0.pre33 lib/vx/common/output_buffer.rb
vx-common-0.2.0.pre32 lib/vx/common/output_buffer.rb
vx-common-0.2.0.pre31 lib/vx/common/output_buffer.rb
vx-common-0.2.0.pre30 lib/vx/common/output_buffer.rb
vx-common-0.2.0.pre29 lib/vx/common/output_buffer.rb
vx-common-0.2.0.pre28 lib/vx/common/output_buffer.rb