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

Make Urlencoded component into an IO object #14

Merged
merged 1 commit into from
May 11, 2017
Merged
Show file tree
Hide file tree
Changes from all 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
19 changes: 8 additions & 11 deletions lib/http/form_data/urlencoded.rb
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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
20 changes: 20 additions & 0 deletions spec/lib/http/form_data/urlencoded_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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