Class: RJR::Messages::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/rjr/messages/response.rb

Overview

Message sent from server to client in response to a JSON-RPC request

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Response

ResponseMessage initializer

Parameters:

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

    options to set on request

Options Hash (args):

  • :message (String)

    json string received from sender

  • :headers (Hash)

    optional headers to set in request and subsequent messages

  • :id (String)

    id to set in response message, should be same as that in received message

  • :result (RJR::Result)

    result of json-rpc method invocation



37
38
39
# File 'lib/rjr/messages/response.rb', line 37

def initialize(args = {})
  parse_args(args)
end

Instance Attribute Details

#headersObject

Optional headers to add to json outside of standard json-rpc request



26
27
28
# File 'lib/rjr/messages/response.rb', line 26

def headers
  @headers
end

#messageObject

Message string received from the source



16
17
18
# File 'lib/rjr/messages/response.rb', line 16

def message
  @message
end

#msg_idObject

ID of the message in accordance w/ json-rpc specification



19
20
21
# File 'lib/rjr/messages/response.rb', line 19

def msg_id
  @msg_id
end

#resultObject

Result encapsulated in the response message

See Also:



23
24
25
# File 'lib/rjr/messages/response.rb', line 23

def result
  @result
end

Class Method Details

.is_response_message?(message) ⇒ true, false

Class helper to determine if the specified string is a valid json-rpc method response

Parameters:

  • message (String)

    string message to check

Returns:

  • (true, false)

    indicating if message is response message



91
92
93
# File 'lib/rjr/messages/response.rb', line 91

def self.is_response_message?(message)
  message.has?('result') || message.has?('error')
end

Instance Method Details

#error_jsonObject



99
100
101
102
103
# File 'lib/rjr/messages/response.rb', line 99

def error_json
  {'error' => {'code'    => @result.error_code,
               'message' => @result.error_msg,
               'class'   => @result.error_class}}
end

#success_jsonObject



95
96
97
# File 'lib/rjr/messages/response.rb', line 95

def success_json
  {'result' => @result.result}
end

#to_json(*a) ⇒ Object

Convert request message to json



106
107
108
109
110
111
112
# File 'lib/rjr/messages/response.rb', line 106

def to_json(*a)
  result_json = @result.success ? success_json : error_json

  {'jsonrpc' => '2.0',
   'id'      => @msg_id}.merge(@headers).
                         merge(result_json).to_json(*a)
end

#to_sObject

Convert request to string format



115
116
117
# File 'lib/rjr/messages/response.rb', line 115

def to_s
  to_json.to_s
end