Skip to content

Commit

Permalink
Encode Spaces in Query Strings as '%20' Instead of '+' (#1125)
Browse files Browse the repository at this point in the history
  • Loading branch information
karlentwistle authored Mar 29, 2020
1 parent b4ad6e3 commit 864a7e5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/faraday/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,20 @@ def build_nested_query(params)
NestedParamsEncoder.encode(params)
end

def default_space_encoding
@default_space_encoding ||= '+'
end

class << self
attr_writer :default_space_encoding
end

ESCAPE_RE = /[^a-zA-Z0-9 .~_-]/.freeze

def escape(str)
str.to_s.gsub(ESCAPE_RE) do |match|
'%' + match.unpack('H2' * match.bytesize).join('%').upcase
end.tr(' ', '+')
end.gsub(' ', default_space_encoding)
end

def unescape(str)
Expand Down
13 changes: 13 additions & 0 deletions spec/faraday/request/url_encoded_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,17 @@
response = conn.post('/echo', 'a' => { 'b' => { 'c' => ['d'] } })
expect(response.body).to eq('a%5Bb%5D%5Bc%5D%5B%5D=d')
end

context 'customising default_space_encoding' do
around do |example|
Faraday::Utils.default_space_encoding = '%20'
example.run
Faraday::Utils.default_space_encoding = nil
end

it 'uses the custom character to encode spaces' do
response = conn.post('/echo', str: 'apple banana')
expect(response.body).to eq('str=apple%20banana')
end
end
end

0 comments on commit 864a7e5

Please sign in to comment.