Sha256: c59e1f3546bbc772310cf9e2aa28872de7ae2f25655501f47caadf4244deb206

Contents?: true

Size: 1.11 KB

Versions: 3

Compression:

Stored size: 1.11 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

    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

3 entries across 3 versions & 1 rubygems

Version Path
pipe_rpc-0.3.0 lib/pipe_rpc/socket.rb
pipe_rpc-0.2.2 lib/pipe_rpc/socket.rb
pipe_rpc-0.2.0 lib/pipe_rpc/socket.rb