Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add indices when arrays are encoded #1399

Merged
merged 1 commit into from
Feb 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions lib/faraday/encoders/nested_params_encoder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,17 @@ def encode_hash(parent, value)
end

def encode_array(parent, value)
new_parent = "#{parent}%5B%5D"
return new_parent if value.empty?
return "#{parent}%5B%5D" if value.empty?

buffer = +''
value.each { |val| buffer << "#{encode_pair(new_parent, val)}&" }
value.each_with_index do |val, index|
new_parent = if @array_indices
"#{parent}%5B#{index}%5D"
else
"#{parent}%5B%5D"
end
buffer << "#{encode_pair(new_parent, val)}&"
end
buffer.chop
end
end
Expand Down Expand Up @@ -161,14 +167,15 @@ def dehash(hash, depth)
# for your requests.
module NestedParamsEncoder
class << self
attr_accessor :sort_params
attr_accessor :sort_params, :array_indices

extend Forwardable
def_delegators :'Faraday::Utils', :escape, :unescape
end

# Useful default for OAuth and caching.
@sort_params = true
@array_indices = false

extend EncodeMethods
extend DecodeMethods
Expand Down
8 changes: 8 additions & 0 deletions spec/faraday/params_encoders/nested_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,14 @@
Faraday::NestedParamsEncoder.sort_params = true
end

it 'encodes arrays indices when asked' do
params = { a: [0, 1, 2] }
expect(subject.encode(params)).to eq('a%5B%5D=0&a%5B%5D=1&a%5B%5D=2')
Faraday::NestedParamsEncoder.array_indices = true
expect(subject.encode(params)).to eq('a%5B0%5D=0&a%5B1%5D=1&a%5B2%5D=2')
Faraday::NestedParamsEncoder.array_indices = false
end

shared_examples 'a wrong decoding' do
it do
expect { subject.decode(query) }.to raise_error(TypeError) do |e|
Expand Down