Class: RPCJSON
- Inherits:
-
Object
- Object
- RPCJSON
- Defined in:
- lib/rpc-json.rb
Overview
Communicate with a JSON RPC server.
Instance Method Summary collapse
-
#call(meth, *args) ⇒ Object
Call the remote method meth with args.
-
#initialize(url) ⇒ RPCJSON
constructor
A new instance of RPCJSON.
-
#method_missing(meth, *args) ⇒ Object
Call call(meth, *args).
Constructor Details
#initialize(url) ⇒ RPCJSON
Returns a new instance of RPCJSON.
11 12 13 |
# File 'lib/rpc-json.rb', line 11 def initialize(url) @url = url end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(meth, *args) ⇒ Object
Call call(meth, *args). If no error is raised, define_singleton_method(meth) to do the same.
44 45 46 47 48 49 50 51 52 53 |
# File 'lib/rpc-json.rb', line 44 def method_missing(meth, *args) ret = call(meth, *args) # Make it so meth shows up in our methods list. unless methods.include?(meth.to_sym) define_singleton_method(meth) { |*args_| call(meth, *args_) } end ret end |
Instance Method Details
#call(meth, *args) ⇒ Object
Call the remote method meth with args. We raise NoMethodError if meth doesn’t exist on the remote side, and RPCJSONError if an error occured on the server.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/rpc-json.rb', line 18 def call(meth, *args) begin resp = RestClient.post(@url, {method: meth, params: args, id: :jsonrpc}.to_json) rescue RestClient::ResourceNotFound => ex if ex.http_code == 404 raise(NoMethodError, "undefined method `#{meth}' for #{self}") else raise end rescue RestClient::InternalServerError => ex if ex.http_code == 500 raise(RPCJSONError, JSON.parse(ex.http_body)['error']['message']) else raise end end parsed = JSON.parse(resp) raise(RPCJSONError, parsed['error']) if parsed['error'] parsed['result'] end |