Skip to content

Commit

Permalink
fix escaping Unicode characters in Ruby 1.8.7
Browse files Browse the repository at this point in the history
In Ruby 1.8, when you are operating with unicode encoding, \w includes
UTF-8 characters such as ☃. Faraday therefore does not escape these
correctly.

Closes #245
  • Loading branch information
Joe Pym authored and mislav committed Mar 24, 2013
1 parent 36379e0 commit ca8c169
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/faraday/parameters.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module Faraday
module NestedParamsEncoder
ESCAPE_RE = /[^\w .~-]+/
ESCAPE_RE = /[^a-zA-Z0-9 .~_-]/

def self.escape(s)
return s.to_s.gsub(ESCAPE_RE) {
Expand Down Expand Up @@ -117,7 +117,7 @@ def self.decode(query)
end

module FlatParamsEncoder
ESCAPE_RE = /[^\w .~-]+/
ESCAPE_RE = /[^a-zA-Z0-9 .~_-]/

def self.escape(s)
return s.to_s.gsub(ESCAPE_RE) {
Expand Down
2 changes: 1 addition & 1 deletion lib/faraday/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def build_nested_query(params)
NestedParamsEncoder.encode(params)
end

ESCAPE_RE = /[^\w .~-]+/
ESCAPE_RE = /[^a-zA-Z0-9 .~_-]/

def escape(s)
s.to_s.gsub(ESCAPE_RE) {
Expand Down
24 changes: 24 additions & 0 deletions test/request_middleware_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,20 @@ def setup
end
end

def with_utf8
if defined?(RUBY_VERSION) && RUBY_VERSION.match(/1.8.\d/)
begin
previous_kcode = $KCODE
$KCODE = "UTF8"
yield
ensure
$KCODE = previous_kcode
end
else
yield
end
end

def test_does_nothing_without_payload
response = @conn.post('/echo')
assert_nil response.headers['Content-Type']
Expand Down Expand Up @@ -66,6 +80,16 @@ def test_url_encoded_unicode
assert err.empty?
end

def test_url_encoded_unicode_with_kcode_set
with_utf8 do
err = capture_warnings {
response = @conn.post('/echo', {:str => "eé cç aã aâ"})
assert_equal "str=e%C3%A9+c%C3%A7+a%C3%A3+a%C3%A2", response.body
}
assert err.empty?
end
end

def test_url_encoded_nested_keys
response = @conn.post('/echo', {'a'=>{'b'=>{'c'=>['d']}}})
assert_equal "a%5Bb%5D%5Bc%5D%5B%5D=d", response.body
Expand Down

0 comments on commit ca8c169

Please sign in to comment.