class RPCJSON

Communicate with a JSON RPC server.

Public Class Methods

new(url) click to toggle source
# File lib/rpc-json.rb, line 11
def initialize(url)
        @url = url
end

Public Instance Methods

call(meth, *args) click to toggle source

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.

# 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
method_missing(meth, *args) click to toggle source

Call call(meth, *args). If no error is raised, define_singleton_method(meth) to do the same.

# 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