Skip to content

Commit

Permalink
Makes parameters sorting configurable (#1162)
Browse files Browse the repository at this point in the history
  • Loading branch information
wishdev committed Jul 7, 2020
1 parent f613099 commit e02a8c1
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 4 deletions.
11 changes: 9 additions & 2 deletions lib/faraday/encoders/flat_params_encoder.rb
Expand Up @@ -33,9 +33,9 @@ def self.encode(params)
key = key.to_s if key.is_a?(Symbol)
[key, value]
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,12 @@ def self.decode(query)
end
end
end

class << self
attr_accessor :sort_params
end

# Useful default for OAuth and caching.
@sort_params = true
end
end
9 changes: 7 additions & 2 deletions lib/faraday/encoders/nested_params_encoder.rb
Expand Up @@ -21,9 +21,9 @@ def encode(params)
key = key.to_s if key.is_a?(Symbol)
[key, value]
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,10 +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

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

extend EncodeMethods
extend DecodeMethods
end
Expand Down
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 e02a8c1

Please sign in to comment.