class JSONClient
JSONClient
auto-converts Hash <-> JSON in request and response.
Constants
- CONTENT_TYPE_JSON
- CONTENT_TYPE_JSON_REGEX
Attributes
content_type_json_request[R]
content_type_json_response_regex[R]
Public Class Methods
new(*args)
click to toggle source
Calls superclass method
HTTPClient::new
# File lib/jsonclient.rb, line 14 def initialize(*args) super @content_type_json_request = CONTENT_TYPE_JSON @content_type_json_response_regex = CONTENT_TYPE_JSON_REGEX end
Public Instance Methods
post(uri, *args, &block)
click to toggle source
# File lib/jsonclient.rb, line 20 def post(uri, *args, &block) request(:post, uri, argument_to_hash_for_json(args), &block) end
put(uri, *args, &block)
click to toggle source
# File lib/jsonclient.rb, line 24 def put(uri, *args, &block) request(:put, uri, argument_to_hash_for_json(args), &block) end
request(method, uri, *args, &block)
click to toggle source
Calls superclass method
HTTPClient#request
# File lib/jsonclient.rb, line 28 def request(method, uri, *args, &block) res = super if @content_type_json_response_regex =~ res.content_type res = wrap_json_response(res) end res end
Private Instance Methods
argument_to_hash_for_json(args)
click to toggle source
# File lib/jsonclient.rb, line 38 def argument_to_hash_for_json(args) hash = argument_to_hash(args, :body, :header, :follow_redirect) if hash[:body].is_a?(Hash) hash[:header] = json_header(hash[:header]) hash[:body] = JSON.generate(hash[:body]) end hash end
json_header(header)
click to toggle source
# File lib/jsonclient.rb, line 47 def json_header(header) header ||= {} if header.is_a?(Hash) header['Content-Type'] = @content_type_json_request else header << ['Content-Type', @content_type_json_request] end header end
wrap_json_response(original)
click to toggle source
# File lib/jsonclient.rb, line 57 def wrap_json_response(original) res = ::HTTP::Message.new_response(JSON.parse(original.content)) res.http_header = original.http_header res.previous = original res end