Class: Protocol::URL::FormData::Parser
- Inherits:
-
Object
- Object
- Protocol::URL::FormData::Parser
- Defined in:
- lib/protocol/url/form_data/parser.rb
Overview
Incrementally parses application/x-www-form-urlencoded form data.
Constant Summary collapse
- CONTENT_TYPE =
"application/x-www-form-urlencoded"- MAXIMUM_TOTAL_SIZE =
The default maximum encoded body size.
2 * 1024 * 1024
- MAXIMUM_PAIR_COUNT =
The default maximum number of form pairs.
1024
Instance Method Summary collapse
-
#each(body) ⇒ Object
Incrementally enumerate URL-encoded form data as ordered name/value pairs.
-
#initialize(maximum_total_size: MAXIMUM_TOTAL_SIZE, maximum_pair_count: MAXIMUM_PAIR_COUNT, maximum_depth: Nested::MAXIMUM_DEPTH) ⇒ Parser
constructor
Initialize the form data parser.
-
#parse(body, result = make_result) ⇒ Object
Parse URL-encoded form data into a nested hash.
Constructor Details
#initialize(maximum_total_size: MAXIMUM_TOTAL_SIZE, maximum_pair_count: MAXIMUM_PAIR_COUNT, maximum_depth: Nested::MAXIMUM_DEPTH) ⇒ Parser
Initialize the form data parser.
26 27 28 29 30 |
# File 'lib/protocol/url/form_data/parser.rb', line 26 def initialize(maximum_total_size: MAXIMUM_TOTAL_SIZE, maximum_pair_count: MAXIMUM_PAIR_COUNT, maximum_depth: Nested::MAXIMUM_DEPTH) @maximum_total_size = maximum_total_size @maximum_pair_count = maximum_pair_count @maximum_depth = maximum_depth end |
Instance Method Details
#each(body) ⇒ Object
Incrementally enumerate URL-encoded form data as ordered name/value pairs.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/protocol/url/form_data/parser.rb', line 53 def each(body) return to_enum(__method__, body) unless block_given? buffer = String.new.b total_size = 0 pair_count = 0 while chunk = body.read break if chunk.empty? total_size += chunk.bytesize check_limit(:total_size, total_size, @maximum_total_size) buffer << chunk while separator = buffer.index("&") assignment = buffer.slice!(0, separator + 1) assignment.chop! unless assignment.empty? pair_count += 1 check_limit(:pair_count, pair_count, @maximum_pair_count) yield_pair(assignment) {|name, value| yield name, value} end end end unless buffer.empty? pair_count += 1 check_limit(:pair_count, pair_count, @maximum_pair_count) yield_pair(buffer) {|name, value| yield name, value} end return true end |
#parse(body, result = make_result) ⇒ Object
Parse URL-encoded form data into a nested hash.
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.
40 41 42 43 44 45 46 47 |
# File 'lib/protocol/url/form_data/parser.rb', line 40 def parse(body, result = make_result) each(body) do |name, value| value = yield(name, value) if block_given? result.add(name, value) end return result.to_h end |