Skip to content
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
13 changes: 8 additions & 5 deletions lib/protocol/url/form_data/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,16 @@ def initialize(maximum_total_size: MAXIMUM_TOTAL_SIZE, maximum_pair_count: MAXIM
# When a block is given, each decoded value is passed through the block before assignment. The value returned by the block is assigned to the result.
#
# @parameter body [Object] A readable body which yields chunks from `#read`.
# @parameter result [Object] The result to populate. It must support `#add` and `#to_h`.
# @yields {|name, value| ...} Each decoded form pair before assignment.
# @returns [Hash] The nested form data.
def parse(body)
nested = Nested.new(maximum_depth: @maximum_depth)

def parse(body, result = make_result)
each(body) do |name, value|
value = yield(name, value) if block_given?
nested.add(name, value)
result.add(name, value)
end

return nested.to_h
return result.to_h
end

# Incrementally enumerate URL-encoded form data as ordered name/value pairs.
Expand Down Expand Up @@ -88,6 +87,10 @@ def each(body)

private

def make_result
return Nested.new(maximum_depth: @maximum_depth)
end

def yield_pair(assignment)
name, value = assignment.split("=", 2)

Expand Down
4 changes: 4 additions & 0 deletions releases.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Releases

## Unreleased

- Allow `Protocol::URL::FormData::Parser#parse` to populate a supplied result object.

## v0.6.0

- Add `Protocol::URL::FormData::Parser` for incremental, limited parsing of `application/x-www-form-urlencoded` form data.
Expand Down
16 changes: 16 additions & 0 deletions test/protocol/url/form_data/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,22 @@ def read
}
end

it "parses form data into a supplied result" do
result = Struct.new(:pairs) do
def add(name, value)
pairs << [name, value]
end

def to_h
return pairs.to_h
end
end.new([])

parameters = parser.parse(StringIO.new("name=Samuel"), result)

expect(parameters).to be == {"name" => "Samuel"}
end

it "distinguishes absent and empty values" do
parameters = parser.parse(StringIO.new("absent&empty="))

Expand Down
Loading