Class: RPC::Encoders::Json::Server

Inherits:
Object
  • Object
show all
Includes:
Errors
Defined in:
lib/rpc/lib/rpc/encoders/json.rb

Instance Method Summary (collapse)

Methods included from Errors

#error, #exception

Instance Method Details

- (Object) decode(binary)



93
94
95
96
97
98
99
100
# File 'lib/rpc/lib/rpc/encoders/json.rb', line 93

def decode(binary)
  object = JSON.parse(binary)
  RPC.log "SERVER DECODE #{object.inspect}"
  object
rescue JSON::ParserError => error
  # This is supposed to result in HTTP 500.
  raise self.exception(error, -32700, "Parse error.")
end

- (Object) encode(response)



135
136
137
138
# File 'lib/rpc/lib/rpc/encoders/json.rb', line 135

def encode(response)
  RPC.log "SERVER ENCODE: #{response.inspect}"
  response.to_json
end

- (Object) execute(encoded_result, subject)



102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/rpc/lib/rpc/encoders/json.rb', line 102

def execute(encoded_result, subject)
  result = self.decode(encoded_result)

  if result.respond_to?(:merge) # Hash, only one result.
    self.encode(result_or_error(subject, result))
  else # Array, multiple results.
    self.encode(
      result.map do |result|
        result_or_error(subject, result)
      end
    )
  end
end

- (Object) response(result, error, id)



131
132
133
# File 'lib/rpc/lib/rpc/encoders/json.rb', line 131

def response(result, error, id)
  {jsonrpc: JSON_RPC_VERSION, result: result, error: error, id: id}
end

- (Object) result_or_error(subject, command)



116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/rpc/lib/rpc/encoders/json.rb', line 116

def result_or_error(subject, command)
  method, args = command["method"], command["params"]
  result = subject.send(method, *args)
  self.response(result, nil, command["id"])
rescue NoMethodError => error
  error = self.exception(error, -32601, "Method not found.")
  self.response(nil, error, command["id"])
rescue ArgumentError => error
  error = self.exception(error, -32602, "Invalid params.")
  self.response(nil, error, command["id"])
rescue Exception => exception
  error = self.exception(exception)
  self.response(nil, error, command["id"])
end