Skip to content

Commit

Permalink
Refactor parameter sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
wishdev committed Jul 1, 2020
1 parent f613099 commit 17dc991
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 2 deletions.
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

0 comments on commit 17dc991

Please sign in to comment.