Skip to content

Commit fa5d47b

Browse files
author
childish-sambino
authored
fix: JSON-encode array request bodies (#118)
1 parent d73aae6 commit fa5d47b

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

Diff for: lib/ruby_http_client.rb

+4-3
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ def wait!
5353
# - +response+ -> A NET::HTTP response object
5454
#
5555
attr_reader :status_code, :body, :headers
56+
5657
def initialize(response)
5758
@status_code = response.code
5859
@body = response.body
@@ -265,7 +266,7 @@ def _(name = nil)
265266
# (e.g. client.name.name.get())
266267
#
267268
# * *Args* :
268-
# - The args are autmoatically passed in
269+
# - The args are automatically passed in
269270
# * *Returns* :
270271
# - Client object or Response object
271272
#
@@ -296,8 +297,8 @@ def build_http_request(http_method)
296297

297298
def update_content_type(http_method)
298299
if @request_body && content_type_json?
299-
# If body is a hash, encode it; else leave it alone
300-
@request.body = if @request_body.class == Hash
300+
# If body is a hash or array, encode it; else leave it alone
301+
@request.body = if [Hash, Array].include?(@request_body.class)
301302
@request_body.to_json
302303
else
303304
@request_body

Diff for: test/test_ruby_http_client.rb

+15-1
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ def test_build_request_post_multipart
189189
assert_equal('hogebody', client.request.body)
190190
end
191191

192-
def test_json_body_encode
192+
def test_json_body_encode_hash
193193
headers = {
194194
'Content-Type' => 'application/json'
195195
}
@@ -203,6 +203,20 @@ def test_json_body_encode
203203
assert_equal('{"this_is":"json"}', response.request_body)
204204
end
205205

206+
def test_json_body_encode_array
207+
headers = {
208+
'Content-Type' => 'application/json'
209+
}
210+
client = MockRequestWithRequestBody.new(
211+
host: 'https://localhost',
212+
request_headers: headers
213+
)
214+
name = 'post'
215+
args = [{ 'request_body' => [{ 'this_is' => 'json' }] }]
216+
response = client.build_request(name, args)
217+
assert_equal('[{"this_is":"json"}]', response.request_body)
218+
end
219+
206220
def test_json_body_do_not_reencode
207221
headers = {
208222
'Content-Type' => 'application/json'

0 commit comments

Comments
 (0)