Class: Cosmos::JsonRpcResponse

Inherits:
JsonRpc show all
Defined in:
lib/cosmos/io/json_rpc.rb

Overview

Represents a JSON Remote Procedure Call Response

Direct Known Subclasses

JsonRpcErrorResponse, JsonRpcSuccessResponse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from JsonRpc

#<=>, #as_json, #to_json

Constructor Details

#initialize(id) ⇒ JsonRpcResponse

Returns a new instance of JsonRpcResponse.

Parameters:

  • id (Integer)

    The identifier which will be matched to the request



240
241
242
243
244
# File 'lib/cosmos/io/json_rpc.rb', line 240

def initialize(id)
  super()
  @hash['jsonrpc'] = "2.0"
  @hash['id'] = id
end

Class Method Details

.from_json(response_data) ⇒ JsonRpcResponse

Creates a JsonRpcResponse object from a JSON encoded String. The version must be 2.0 and the JSON must include the id members. It must also include either result for success or error for failure but never both.

Parameters:

  • response_data (String)

    JSON encoded string representing the response

Returns:



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/cosmos/io/json_rpc.rb', line 252

def self.from_json(response_data)
  msg = "Invalid JSON-RPC 2.0 Response"
  begin
    hash = JSON.parse(response_data, :allow_nan => true, :create_additions => true)
  rescue
    raise msg
  end

  # Verify the jsonrpc version is correct and there is an ID
  raise msg unless hash['jsonrpc'] == "2.0" and hash.key?('id')
  # If there is a result this is probably a good response
  if hash.key?('result')
    # Can't have an error key in a good response
    raise msg if hash.key?('error')
    JsonRpcSuccessResponse.from_hash(hash)
  elsif hash.key?('error')
    # There was an error key so create an error response
    JsonRpcErrorResponse.from_hash(hash)
  else
    # Neither a result or error key so raise exception
    raise msg
  end
end