diff --git a/lib/http/form_data/urlencoded.rb b/lib/http/form_data/urlencoded.rb index 2e3cc04..4a685d0 100644 --- a/lib/http/form_data/urlencoded.rb +++ b/lib/http/form_data/urlencoded.rb @@ -1,21 +1,20 @@ # frozen_string_literal: true +require "http/form_data/readable" + require "uri" +require "stringio" module HTTP module FormData # `application/x-www-form-urlencoded` form data. class Urlencoded + include Readable + # @param [#to_h, Hash] data form data key-value Hash def initialize(data) - @data = FormData.ensure_hash data - end - - # Returns content to be used for HTTP request body. - # - # @return [String] - def to_s - ::URI.encode_www_form @data + uri_encoded_data = ::URI.encode_www_form FormData.ensure_hash(data) + @io = StringIO.new(uri_encoded_data) end # Returns MIME type to be used for HTTP request `Content-Type` header. @@ -29,9 +28,7 @@ def content_type # `Content-Length` header. # # @return [Integer] - def content_length - to_s.bytesize - end + alias content_length size end end end diff --git a/spec/lib/http/form_data/urlencoded_spec.rb b/spec/lib/http/form_data/urlencoded_spec.rb index 3279ab0..d0211b0 100644 --- a/spec/lib/http/form_data/urlencoded_spec.rb +++ b/spec/lib/http/form_data/urlencoded_spec.rb @@ -29,4 +29,24 @@ it { is_expected.to eq "foo%5Bbar%5D=%D1%82%D0%B5%D1%81%D1%82" } end end + + describe "#size" do + it "returns bytesize of multipart data" do + expect(form_data.size).to eq form_data.to_s.bytesize + end + end + + describe "#read" do + it "returns multipart data" do + expect(form_data.read).to eq form_data.to_s + end + end + + describe "#rewind" do + it "rewinds the multipart data IO" do + form_data.read + form_data.rewind + expect(form_data.read).to eq form_data.to_s + end + end end