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



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

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

.parse(raw, boundary) ⇒ Object



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

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