Sha256: ab304ed6bef13a87c10a292db3a44f0eed9e76cd05d11ded77422a9d790df621

Contents?: true

Size: 1.17 KB

Versions: 2

Compression:

Stored size: 1.17 KB

Contents

module PipeRpc
  class Socket
    def initialize(hub, args = {})
      @hub = hub
      @input = args.fetch(:input)
      @output = args.fetch(:output)
      on_write{}
      on_read{}
    end

    def read
      symbolize_message_keys(JSON.load(@input.gets)).tap do |message|
        next if message[:server] == 'reflect_logger'
        @hub.log "received: #{message.inspect}"
        @on_read.call(message)
      end
    end

    def write(obj)
      raise InternalError.new('Output pipe broke') if @output.closed?
      @output.puts(JSON.dump(obj.to_h.tap do |message|
        next if @hub.logger == :reflect
        @hub.log "sent: #{message.inspect}"
        @on_write.call(message)
      end))
    end

    def on_write(&on_write)
      @on_write = on_write || proc{}
    end

    def on_read(&on_read)
      @on_read = on_read || proc{}
    end

    def close
      @input.close
      @output.close
    end

    private

    def symbolize_message_keys(message)
      hash = message.symbolize_keys
      hash[:error] = hash[:error].symbolize_keys if hash[:error]
      hash[:error][:data] = hash[:error][:data].symbolize_keys if hash[:error] and hash[:error][:data]
      hash
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
pipe_rpc-0.3.2 lib/pipe_rpc/socket.rb
pipe_rpc-0.3.1 lib/pipe_rpc/socket.rb