Skip to content

Commit

Permalink
Allow override Urlencoded encoder implementation
Browse files Browse the repository at this point in the history
``` ruby
HTTP::FormData::Urlencoded.encoder = lambda do |enum|
  unescaped_chars = /[^a-z0-9\-\.\_\~]/i
  parts = []

  enum.each do |k, v|
    k = ::URI::DEFAULT_PARSER.escape(k.to_s, unescaped_chars)

    if v.nil?
      parts << k
    elsif v.respond_to?(:to_ary)
      v.to_ary.each do |vv|
        vv = ::URI::DEFAULT_PARSER.escape(v.to_s, unescaped_chars)
        parts << "#{k}=#{vv}"
      end
    else
      v = ::URI::DEFAULT_PARSER.escape(v.to_s, unescaped_chars)
      parts << "#{k}=#{v}"
    end
  end

  parts.join("&")
end
```
  • Loading branch information
FabienChaynes authored and ixti committed May 31, 2018
1 parent e938a40 commit 3bf2e83
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/http/form_data/urlencoded.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,17 @@ module FormData
class Urlencoded
include Readable

class << self
attr_writer :encoder

def encoder
@encoder ||= ::URI.method(:encode_www_form)
end
end

# @param [#to_h, Hash] data form data key-value Hash
def initialize(data)
uri_encoded_data = ::URI.encode_www_form FormData.ensure_hash(data)
@io = StringIO.new(uri_encoded_data)
@io = StringIO.new(self.class.encoder.call(FormData.ensure_hash(data)))
end

# Returns MIME type to be used for HTTP request `Content-Type` header.
Expand Down
9 changes: 9 additions & 0 deletions spec/lib/http/form_data/urlencoded_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,13 @@
expect(form_data.read).to eq form_data.to_s
end
end

describe ".encoder=" do
before { described_class.encoder = ::JSON.method(:dump) }
after { described_class.encoder = ::URI.method(:encode_www_form) }

it "switches form encoder implementation" do
expect(form_data.to_s).to eq('{"foo[bar]":"test"}')
end
end
end

0 comments on commit 3bf2e83

Please sign in to comment.