Class: Rets::Parser::Multipart

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

Overview

Inspired by Mail.

Defined Under Namespace

Classes: Part

Constant Summary collapse

CRLF =
"\r\n"
WSP =
"\s"
HEADER_LINE =
/^([!-9;-~]+:\s*.+)$/

Class Method Summary collapse

Class Method Details

.check_for_invalids_parts!(parts) ⇒ Object



33
34
35
36
# File 'lib/rets/parser/multipart.rb', line 33

def self.check_for_invalids_parts!(parts)
  return unless parts.length == 1 && parts.first.headers['content-type'] == 'text/xml'
  ErrorChecker.check(parts.first)
end

.parse(raw, boundary) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/rets/parser/multipart.rb', line 11

def self.parse(raw, boundary)
  parts = []
  boundary_regexp = /--#{Regexp.quote(boundary)}(--)?#{CRLF}/

  # WTF some RETS servers declare response body including jpeg binary is encoded in utf8
  raw.force_encoding 'ascii-8bit' if raw.respond_to?(:force_encoding)

  raw.split(boundary_regexp).each do |chunk|
    header_part, body_part = chunk.split(/#{CRLF}#{WSP}*#{CRLF}/m, 2)

    if header_part =~ HEADER_LINE
      headers = header_part.split(/\r\n/).map { |kv| p = kv.split(/:\s?/); [p[0].downcase, p[1..-1].join(':')] }
      headers = Hash[*headers.flatten]
      parts << Part.new(headers, body_part)
    else
      next # not a valid chunk.
    end
  end
  check_for_invalids_parts!(parts)
  parts
end