diff --git a/lib/http/form_data/urlencoded.rb b/lib/http/form_data/urlencoded.rb index 4a685d0..ccb05b0 100644 --- a/lib/http/form_data/urlencoded.rb +++ b/lib/http/form_data/urlencoded.rb @@ -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. diff --git a/spec/lib/http/form_data/urlencoded_spec.rb b/spec/lib/http/form_data/urlencoded_spec.rb index 43fe6ad..a3de752 100644 --- a/spec/lib/http/form_data/urlencoded_spec.rb +++ b/spec/lib/http/form_data/urlencoded_spec.rb @@ -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