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

Refactor parameter sorting #1162

Merged
merged 2 commits into from Jul 7, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/faraday/encoders/flat_params_encoder.rb
Expand Up @@ -35,7 +35,7 @@ def self.encode(params)
end
# Useful default for OAuth and caching.
# Only to be used for non-Array inputs. Arrays should preserve order.
params.sort!
params.sort! if @sort_params
end

# The params have form [['key1', 'value1'], ['key2', 'value2']].
Expand Down Expand Up @@ -94,5 +94,11 @@ def self.decode(query)
end
end
end

class << self
attr_accessor :sort_params
end
end

FlatParamsEncoder.sort_params = true
end
6 changes: 5 additions & 1 deletion lib/faraday/encoders/nested_params_encoder.rb
Expand Up @@ -23,7 +23,7 @@ def encode(params)
end
# Useful default for OAuth and caching.
# Only to be used for non-Array inputs. Arrays should preserve order.
params.sort!
params.sort! if @sort_params
end

# The params have form [['key1', 'value1'], ['key2', 'value2']].
Expand Down Expand Up @@ -161,11 +161,15 @@ def dehash(hash, depth)
# for your requests.
module NestedParamsEncoder
class << self
attr_accessor :sort_params

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

extend EncodeMethods
extend DecodeMethods
end

NestedParamsEncoder.sort_params = true
end
8 changes: 8 additions & 0 deletions spec/faraday/params_encoders/flat_spec.rb
Expand Up @@ -31,4 +31,12 @@
params = { a: [] }
expect(subject.encode(params)).to eq('a=')
end

it 'encodes unsorted when asked' do
params = { b: false, a: true }
expect(subject.encode(params)).to eq('a=true&b=false')
Faraday::FlatParamsEncoder.sort_params = false
expect(subject.encode(params)).to eq('b=false&a=true')
Faraday::FlatParamsEncoder.sort_params = true
end
end
8 changes: 8 additions & 0 deletions spec/faraday/params_encoders/nested_spec.rb
Expand Up @@ -94,6 +94,14 @@
expect(subject.encode(params)).to eq('a%5B%5D=true&a%5B%5D=false')
end

it 'encodes unsorted when asked' do
params = { b: false, a: true }
expect(subject.encode(params)).to eq('a=true&b=false')
Faraday::NestedParamsEncoder.sort_params = false
expect(subject.encode(params)).to eq('b=false&a=true')
Faraday::NestedParamsEncoder.sort_params = true
end

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