Class: JSONRPC::Request

Inherits:
Dry::Struct
  • Object
show all
Defined in:
lib/jsonrpc/request.rb

Overview

A JSON-RPC 2.0 Request object

Represents a call to a specific method with optional parameters and an identifier.

Examples:

Create a request with positional parameters

request = JSONRPC::Request.new(method: "subtract", params: [42, 23], id: 1)

Create a request with named parameters

request = JSONRPC::Request.new(method: "subtract", params: { minuend: 42, subtrahend: 23 }, id: 3)

Instance Method Summary collapse

Instance Method Details

#idString, ...

The request identifier

Examples:

request.id # => 1

Returns:

  • (String, Integer, nil)


59
# File 'lib/jsonrpc/request.rb', line 59

attribute? :id, Types::String | Types::Integer | Types::Nil

#jsonrpcString

JSON-RPC protocol version

Examples:

request.jsonrpc # => "2.0"

Returns:

  • (String)


26
# File 'lib/jsonrpc/request.rb', line 26

attribute :jsonrpc, Types::String.default('2.0')

#methodString

The method name to invoke

Examples:

request.method # => "subtract"

Returns:

  • (String)


37
# File 'lib/jsonrpc/request.rb', line 37

attribute :method, Types::String.constrained(format: /\A(?!rpc\.)/)

#paramsHash, ...

Parameters to pass to the method

Examples:

request.params # => { "minuend": 42, "subtrahend": 23 }

Returns:

  • (Hash, Array, nil)


48
# File 'lib/jsonrpc/request.rb', line 48

attribute? :params, (Types::Hash | Types::Array).optional

#to_hHash

Converts the request to a JSON-compatible Hash

Examples:

request.to_h
# => { jsonrpc: "2.0", method: "subtract", params: [42, 23], id: 1 }

Returns:

  • (Hash)

    the request as a JSON-compatible Hash



71
72
73
74
75
76
77
78
79
80
# File 'lib/jsonrpc/request.rb', line 71

def to_h
  hash = {
    jsonrpc: jsonrpc,
    method: method,
    id: id
  }

  hash[:params] = params unless params.nil?
  hash
end

#to_jsonString

Converts the request to a JSON string

Examples:

request.to_json
# => '{"jsonrpc":"2.0","method":"subtract","params":[42,23],"id":1}'

Returns:

  • (String)

    the request as a JSON string



92
93
94
# File 'lib/jsonrpc/request.rb', line 92

def to_json(*)
  MultiJson.dump(to_h, *)
end