Skip to content

Commit

Permalink
Encode false to "false" in Faraday::Request::Json
Browse files Browse the repository at this point in the history
Previously, `Faraday::Request::Json` doesn't encode the value `false`
while it encodes `true` to `"true"`.

This patch fixes the inconsistent behavior to make the middleware encode
`false` to `"false"`.
  • Loading branch information
yykamei committed May 23, 2023
1 parent 111d354 commit 1ec56a0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/faraday/request/json.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,16 @@ def process_request?(env)
end

def body?(env)
(body = env[:body]) && !(body.respond_to?(:to_str) && body.empty?)
body = env[:body]
case body
when true, false
true
when nil
# NOTE: nil can be converted to `"null"`, but this middleware doesn't process `nil` for the compatibility.
false
else
!(body.respond_to?(:to_str) && body.empty?)
end
end

def request_type(env)
Expand Down
24 changes: 24 additions & 0 deletions spec/faraday/request/json_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,30 @@ def result_type
end
end

context 'true body' do
let(:result) { process(true) }

it 'encodes body' do
expect(result_body).to eq('true')
end

it 'adds content type' do
expect(result_type).to eq('application/json')
end
end

context 'false body' do
let(:result) { process(false) }

it 'encodes body' do
expect(result_body).to eq('false')
end

it 'adds content type' do
expect(result_type).to eq('application/json')
end
end

context 'object body with json type' do
let(:result) { process({ a: 1 }, 'application/json; charset=utf-8') }

Expand Down

0 comments on commit 1ec56a0

Please sign in to comment.