Class: JSON_RPC::Response

Inherits:
Data
  • Object
show all
Defined in:
lib/json_rpc/response.rb

Overview

Represents a JSON-RPC response object.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id:, **kwargs) ⇒ Response

Initializes a new Response.

Parameters:

  • id (String, Numeric, nil)

    The request identifier. Must match the request ID.

  • result (Object, nil)

    The result data (if successful).

  • error (Hash, JSON_RPC::JsonRpcError, Symbol, nil)

    The error object/symbol (if failed).

Raises:

  • (ArgumentError)

    if both result and error are provided, or neither is provided for non-null id.



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/json_rpc/response.rb', line 12

def initialize(id:, **kwargs)
  # Check which parameters were actually provided
  has_result = kwargs.key?(:result)
  has_error = kwargs.key?(:error)

  result = kwargs[:result]
  error = kwargs[:error]

  validate_response(id, has_result, has_error, result, error)
  error_obj = process_error(error)

  super(id: id, result: result, error: error_obj)
end

Instance Attribute Details

#errorObject (readonly)

Returns the value of attribute error

Returns:

  • (Object)

    the current value of error



5
6
7
# File 'lib/json_rpc/response.rb', line 5

def error
  @error
end

#idObject (readonly)

Returns the value of attribute id

Returns:

  • (Object)

    the current value of id



5
6
7
# File 'lib/json_rpc/response.rb', line 5

def id
  @id
end

#resultObject (readonly)

Returns the value of attribute result

Returns:

  • (Object)

    the current value of result



5
6
7
# File 'lib/json_rpc/response.rb', line 5

def result
  @result
end

Class Method Details

.from_h(h) ⇒ Object



26
27
28
29
30
31
# File 'lib/json_rpc/response.rb', line 26

def self.from_h(h)
  args = { id: h["id"] }
  args[:result] = h["result"] if h.key?("result")
  args[:error] = h["error"] if h.key?("error")
  new(**args)
end

Instance Method Details

#as_jsonObject



47
# File 'lib/json_rpc/response.rb', line 47

def as_json(*) = to_h

#to_hHash

Returns a hash representation of the response, ready for JSON serialization.

Returns:

  • (Hash)

    The hash representation.



36
37
38
39
40
41
42
43
44
45
# File 'lib/json_rpc/response.rb', line 36

def to_h
  hash = { "jsonrpc" => "2.0", id: id }
  if error
    hash[:error] = error # error is already a hash here
  else
    # Result must be included, even if null, for successful responses
    hash[:result] = result
  end
  hash
end