Class: Nanook::Rpc

Inherits:
Object
  • Object
show all
Defined in:
lib/nanook/rpc.rb

Overview

The Nanook::Rpc class is responsible for maintaining the connection to the RPC server, calling the RPC and parsing its response into Ruby primitives.

Internally, the Nanook class creates an instance of this class, and it's generally more convenient to interact with the RPC through an instance of #rpc instead of by instantiating this class directly:

nanook = Nanook.new
nanook.rpc(:accounts_create, wallet: wallet_id, count: 2)

Constant Summary

DEFAULT_URI =

Default RPC server and port to connect to

"http://localhost:7076"
DEFAULT_TIMEOUT =

Default request timeout in seconds

60

Instance Method Summary collapse

Constructor Details

#initialize(uri = DEFAULT_URI, timeout: DEFAULT_TIMEOUT) ⇒ Rpc

Returns a new instance of Rpc



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/nanook/rpc.rb', line 23

def initialize(uri=DEFAULT_URI, timeout:DEFAULT_TIMEOUT)
  @rpc_server = URI(uri)

  unless ['http', 'https'].include?(@rpc_server.scheme)
    raise ArgumentError.new("URI must have http or https in it. Was given: #{uri}")
  end

  @http = Net::HTTP.new(@rpc_server.host, @rpc_server.port)
  @http.read_timeout = timeout
  @request = Net::HTTP::Post.new(@rpc_server.request_uri, {"user-agent" => "Ruby nanook gem"})
  @request.content_type = "application/json"
end

Instance Method Details

#call(action, params = {}) ⇒ Hash

Calls the RPC server and returns the response.

Parameters:

  • action (Symbol)

    the “action” of the RPC to call. The RPC always expects an “action” param to identify what RPC action is being called.

  • params (Hash) (defaults to: {})

    all other params to pass to the RPC

Returns:

  • (Hash)

    the response from the RPC



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/nanook/rpc.rb', line 42

def call(action, params={})
  # Stringify param values
  params = Hash[params.map {|k, v| [k, v.to_s] }]

  @request.body = { action: action }.merge(params).to_json

  response = @http.request(@request)

  if response.is_a?(Net::HTTPSuccess)
    hash = JSON.parse(response.body)
    process_hash(hash)
  else
    raise Nanook::Error.new("Encountered net/http error #{response.code}: #{response.class.name}")
  end
end

#inspectString

Returns:

  • (String)


59
60
61
# File 'lib/nanook/rpc.rb', line 59

def inspect
  "#{self.class.name}(host: \"#{@rpc_server}\", timeout: #{@http.read_timeout} object_id: \"#{"0x00%x" % (object_id << 1)}\")"
end