Skip to content

Commit

Permalink
Merge pull request #5 from NARKOZ/refactor-readbility
Browse files Browse the repository at this point in the history
Refactor for readability
  • Loading branch information
ramontayag authored Nov 21, 2018
2 parents 70b4b4f + 22fcf67 commit c2b919d
Showing 1 changed file with 30 additions and 26 deletions.
56 changes: 30 additions & 26 deletions lib/bitcoiner/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

module Bitcoiner
class Client

DEFAULT_ID = 'jsonrpc'.freeze

attr_accessor :endpoint, :username, :password

def initialize(user, pass, host)
Expand All @@ -24,44 +27,45 @@ def accounts

def request(method_or_array_of_methods, *args)
if method_or_array_of_methods.is_a?(Array)
post_body = method_or_array_of_methods.map do |m|
{
'method' => m[0],
'params' => m[1],
'id' => 'jsonrpc'
}
end
batch_request(method_or_array_of_methods)
else
post_body = {
'method' => method_or_array_of_methods,
'params' => args,
'id' => 'jsonrpc'
}
single_request(method_or_array_of_methods, *args)
end
end

def inspect
"#<Bitcoiner::Client #{endpoint.inspect} #{username}:#{password} >"
end

class JSONRPCError < RuntimeError; end

private

response = Typhoeus.post(
def post(body)
Typhoeus.post(
endpoint,
userpwd: [username, password].join(":"),
body: post_body.to_json,
body: body.to_json,
)
end

parsed_response = parse_body(response)

if parsed_response.is_a?(Hash)
raise JSONRPCError, parsed_response['error'] if parsed_response['error']
return parsed_response['result']
def batch_request(methods_and_args)
post_body = methods_and_args.map do |method, args|
{ 'method' => method, 'params' => args, 'id' => DEFAULT_ID }
end

parsed_response
response = post(post_body)
parse_body(response)
end

def inspect
"#<Bitcoiner::Client #{endpoint.inspect} #{username}:#{password} >"
end
def single_request(method, *args)
post_body = { 'method' => method, 'params' => args, 'id' => DEFAULT_ID }
response = post(post_body)
parsed_response = parse_body(response)

class JSONRPCError < RuntimeError; end
raise JSONRPCError, parsed_response['error'] if parsed_response['error']

private
parsed_response['result']
end

def parse_body(response)
if response.success?
Expand Down

0 comments on commit c2b919d

Please sign in to comment.