Class: Philiprehberger::Multipart::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/multipart/parser.rb

Overview

Parses multipart/form-data request bodies into Part objects

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(body, content_type) ⇒ Parser

Returns a new instance of Parser.

Parameters:

  • body (String)

    the raw multipart body

  • content_type (String)

    the Content-Type header value



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.

Parameters:

  • body (String)

    the raw multipart body

  • content_type (String)

    the Content-Type header value (must include boundary)

Returns:

  • (Array<Part>)

    parsed parts

Raises:

  • (Error)

    if the boundary cannot be extracted or the body is malformed



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

#parseArray<Part>

Parse the multipart body into Part objects

Returns:

  • (Array<Part>)

    parsed parts



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