Class: Rets::Parser::Compact

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

Constant Summary collapse

TAB =
/\t/
INCLUDE_NULL_FIELDS =
-1
InvalidDelimiter =
Class.new(ArgumentError)

Class Method Summary collapse

Class Method Details

.columnsObject



32
33
34
# File 'lib/rets/parser/compact.rb', line 32

def self.columns
  @columns
end

.columns=(columns, delimiter = TAB) ⇒ Object



28
29
30
# File 'lib/rets/parser/compact.rb', line 28

def self.columns=(columns, delimiter = TAB)
  @columns = columns.split(delimiter)
end

.parse(data, delimiter = TAB) ⇒ Object

Parses a single row of RETS-COMPACT data.

Delimiter must be a regexp because String#split behaves differently when given a string pattern. (It removes leading spaces).

Raises:

  • (ArgumentError)


45
46
47
48
49
50
51
# File 'lib/rets/parser/compact.rb', line 45

def self.parse(data, delimiter = TAB)
  raise ArgumentError, "Delimiter must be a regular expression" unless Regexp === delimiter

  hash = {}
  data.split(delimiter, INCLUDE_NULL_FIELDS).each_with_index { |v, i| hash[columns[i]] = v.to_s unless v.to_s.empty? }
  hash
end

.parse_count(xml) ⇒ Object



36
37
38
# File 'lib/rets/parser/compact.rb', line 36

def self.parse_count(xml)
  Nokogiri.parse(xml).at("//COUNT").attribute("Records").value.to_i
end

.parse_document(xml) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rets/parser/compact.rb', line 10

def self.parse_document(xml)
  doc = Nokogiri.parse(xml.to_s)

  delimiter = doc.at("//DELIMITER")
  delimiter = delimiter ? Regexp.new(Regexp.escape(delimiter.attr(:value).to_i.chr)) : TAB

  if delimiter == // || delimiter == /,/
    raise InvalidDelimiter, "Empty or invalid delimiter found, unable to parse."
  end

  self.columns = doc.at("//COLUMNS").text
  rows = doc.xpath("//DATA")

  rows.map.with_index do |data, i|
    parse(data.text, delimiter)
  end
end