Sha256: c6ebac950407e670e7bfcf414398fffc21242ef398ab74975ea081397fa4d47f

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents

module Backport
  class Client
    def initialize input, output, adapter
      @in = input
      @out = output
      # @todo Adapter can either be an Adapter class or a module
      @adapter = make_adapter(adapter)
      @stopped = true
      @buffer = ''
    end

    def stopped?
      @stopped ||= false
    end

    def stop
      return if stopped?
      @adapter.closing
      @stopped = true
    end

    def run
      return unless stopped?
      @stopped = false
      @adapter.opening
      run_input_thread
    end

    def sending data
      @adapter.sending data
    end

    def read
      tmp = nil
      mutex.synchronize do
        tmp = @buffer.dup
        @buffer.clear
      end
      return tmp unless tmp.empty?
    end

    private

    def make_adapter cls_mod
      if cls_mod.is_a?(Class)
        @adapter = cls_mod.new(@out)
      elsif cls_mod.is_a?(Module)
        @adapter = Adapter.new(@out)
        @adapter.extend cls_mod
      else
        raise TypeError, "#{cls_mod} is not a valid Backport adapter"
      end
    end

    def mutex
      @mutex ||= Mutex.new
    end

    def run_input_thread
      Thread.new do
        until stopped?
          char = @in.getc
          if char.nil?
            STDERR.puts "Client received nil. Stopping"
            stop
            break
          end
          mutex.synchronize { @buffer.concat char }
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
backport-0.1.0 lib/backport/client.rb