From 3077b9b026fba617f712b476602afce9eb3bb74c Mon Sep 17 00:00:00 2001 From: Sam Harrison Date: Mon, 24 Feb 2020 10:43:11 -0600 Subject: [PATCH] fix: JSON-encode array request bodies --- lib/ruby_http_client.rb | 7 ++++--- test/test_ruby_http_client.rb | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/lib/ruby_http_client.rb b/lib/ruby_http_client.rb index f7fe5cb..d0fff4d 100644 --- a/lib/ruby_http_client.rb +++ b/lib/ruby_http_client.rb @@ -53,6 +53,7 @@ def wait! # - +response+ -> A NET::HTTP response object # attr_reader :status_code, :body, :headers + def initialize(response) @status_code = response.code @body = response.body @@ -265,7 +266,7 @@ def _(name = nil) # (e.g. client.name.name.get()) # # * *Args* : - # - The args are autmoatically passed in + # - The args are automatically passed in # * *Returns* : # - Client object or Response object # @@ -296,8 +297,8 @@ def build_http_request(http_method) def update_content_type(http_method) if @request_body && content_type_json? - # If body is a hash, encode it; else leave it alone - @request.body = if @request_body.class == Hash + # If body is a hash or array, encode it; else leave it alone + @request.body = if [Hash, Array].include?(@request_body.class) @request_body.to_json else @request_body diff --git a/test/test_ruby_http_client.rb b/test/test_ruby_http_client.rb index 6ae8f46..7f91029 100644 --- a/test/test_ruby_http_client.rb +++ b/test/test_ruby_http_client.rb @@ -189,7 +189,7 @@ def test_build_request_post_multipart assert_equal('hogebody', client.request.body) end - def test_json_body_encode + def test_json_body_encode_hash headers = { 'Content-Type' => 'application/json' } @@ -203,6 +203,20 @@ def test_json_body_encode assert_equal('{"this_is":"json"}', response.request_body) end + def test_json_body_encode_array + headers = { + 'Content-Type' => 'application/json' + } + client = MockRequestWithRequestBody.new( + host: 'https://localhost', + request_headers: headers + ) + name = 'post' + args = [{ 'request_body' => [{ 'this_is' => 'json' }] }] + response = client.build_request(name, args) + assert_equal('[{"this_is":"json"}]', response.request_body) + end + def test_json_body_do_not_reencode headers = { 'Content-Type' => 'application/json'