Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to pass encoder to HTTP::FormData::Urlencoded instance #29

Merged
merged 5 commits into from
Mar 3, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions lib/http/form_data.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,14 @@ class << self
# @param [#to_h, Hash] data
# @return [Multipart] if any of values is a {FormData::File}
# @return [Urlencoded] otherwise
def create(data)
data = ensure_hash data
klass = multipart?(data) ? Multipart : Urlencoded
def create(data, encoder: nil)
data = ensure_hash data

klass.new data
if multipart?(data)
Multipart.new(data)
else
Urlencoded.new(data, encoder)
end
end

# Coerce `obj` to Hash.
Expand Down
5 changes: 3 additions & 2 deletions lib/http/form_data/urlencoded.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,9 @@ def encoder
end

# @param [#to_h, Hash] data form data key-value Hash
def initialize(data)
@io = StringIO.new(self.class.encoder.call(FormData.ensure_hash(data)))
def initialize(data, encoder = nil)
encoder ||= self.class.encoder
@io = StringIO.new(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 @@ -64,4 +64,13 @@
expect(form_data.to_s).to eq('{"foo[bar]":"test"}')
end
end

context "with custom instance level encoder" do
let(:encoder) { proc { |data| ::JSON.dump(data) } }
subject(:form_data) { HTTP::FormData::Urlencoded.new(data, encoder) }

it "uses encoder passed to initializer" do
expect(form_data.to_s).to eq('{"foo[bar]":"test"}')
end
end
end