Class: Philiprehberger::Multipart::Parser
- Inherits:
-
Object
- Object
- Philiprehberger::Multipart::Parser
- Defined in:
- lib/philiprehberger/multipart/parser.rb
Overview
Parses multipart/form-data request bodies into Part objects
Class Method Summary collapse
-
.parse(body, content_type:) ⇒ Array<Part>
Parsed parts.
Instance Method Summary collapse
-
#initialize(body, content_type) ⇒ Parser
constructor
A new instance of Parser.
-
#parse ⇒ Array<Part>
Parse the multipart body into Part objects.
Constructor Details
#initialize(body, content_type) ⇒ Parser
Returns a new instance of Parser.
17 18 19 20 |
# File 'lib/philiprehberger/multipart/parser.rb', line 17 def initialize(body, content_type) @body = body.b @boundary = extract_boundary(content_type) end |
Class Method Details
.parse(body, content_type:) ⇒ Array<Part>
Returns parsed parts.
11 12 13 |
# File 'lib/philiprehberger/multipart/parser.rb', line 11 def self.parse(body, content_type:) new(body, content_type).parse end |
Instance Method Details
#parse ⇒ Array<Part>
Parse the multipart body into Part objects
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/philiprehberger/multipart/parser.rb', line 25 def parse delimiter = "--#{@boundary}" raw = @body.split(delimiter) raw.shift # discard preamble before first boundary raw.each_with_object([]) do |segment, parts| segment = segment.sub(/\A\r\n/, '') next if segment.start_with?('--') # closing boundary next if segment.strip.empty? # Strip trailing CRLF that precedes the next boundary segment = segment.sub(/\r\n\z/, '') headers_section, body_content = split_headers_and_body(segment) next if headers_section.nil? headers = parse_headers(headers_section) disposition = headers['content-disposition'] || '' name = extract_param(disposition, 'name') filename = extract_param(disposition, 'filename') part_content_type = headers['content-type'] parts << Part.new( name&.to_sym || :unknown, body_content || '', filename: filename, content_type: part_content_type ) end end |