Class: Jr::Jr

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

Overview

Jr lets you communicate with an HTTP JSON RPC server.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port, user = nil, password = nil, ssl = false) ⇒ Jr

Returns a new instance of Jr.



79
80
81
82
83
# File 'lib/jr.rb', line 79

def initialize(host, port, user=nil, password=nil, ssl=false)
	%w{host user port password ssl}.each do |var|
		instance_variable_set("@#{var}", eval(var))
	end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args) ⇒ Object



114
115
116
# File 'lib/jr.rb', line 114

def method_missing(meth, *args)
	request(meth, *args)
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



77
78
79
# File 'lib/jr.rb', line 77

def connection
  @connection
end

#hostObject (readonly)

Returns the value of attribute host.



74
75
76
# File 'lib/jr.rb', line 74

def host
  @host
end

#passwordObject (readonly)

Returns the value of attribute password.



74
75
76
# File 'lib/jr.rb', line 74

def password
  @password
end

#portObject (readonly)

Returns the value of attribute port.



74
75
76
# File 'lib/jr.rb', line 74

def port
  @port
end

#sslObject (readonly)

Returns the value of attribute ssl.



74
75
76
# File 'lib/jr.rb', line 74

def ssl
  @ssl
end

#userObject (readonly)

Returns the value of attribute user.



74
75
76
# File 'lib/jr.rb', line 74

def user
  @user
end

Instance Method Details

#request(method, *args) ⇒ Object

Call method on the server, and return the result.



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/jr.rb', line 86

def request(method, *args)
	if method.to_s.start_with?('rpc')
		raise ReservedMethod.new(method)
	end

	reqid = get_request_id()
	data = JSON.dump(
		jsonrpc: '2.0',
		method: method.to_s,
		params: args,
		id: reqid
	)

	r = parse_json_data(http_request(data))
	if r.has_key?('jsonrpc') and (r['jsonrpc'] != JSON_RPC_VERSION)
		# Even though the JSON RPC specification requires that a 'jsonrpc' key
		# is present, we don't require it because not all servers implement it.
		raise ProtocolMismatch.new(self, r['jsonrpc'])
	elsif r['id'] != reqid
		raise IDMismatch.new(self)
	elsif r['error']
		raise ServerError.new(self, r['error']['code'], r['error']['message'],
		                      r['error']['data'])
	end

	r['result']
end