Class: XMLMunger::Parser

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(xml, nori_options = {}) ⇒ Parser

Returns a new instance of Parser.



8
9
10
11
12
13
14
15
16
17
# File 'lib/xmlmunger/parser.rb', line 8

def initialize xml, nori_options = {}
  unless xml.is_a?(Hash)
    unless xml.is_a?(String)
      raise ArgumentError.new("Argument xml should be a Hash or String (XML file).")
    end
    @xml = ::Nori.new(NoriConstants.default_options.merge(nori_options)).parse(xml)
  else
    @xml = xml
  end
end

Instance Attribute Details

#xmlObject

Returns the value of attribute xml.



6
7
8
# File 'lib/xmlmunger/parser.rb', line 6

def xml
  @xml
end

Instance Method Details

#run(options = {}) ⇒ Object

Raises:

  • (TypeError)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/xmlmunger/parser.rb', line 19

def run options = {}
  # prepare the options hash
  raise TypeError.new("options argument must be a hash") unless options.is_a?(Hash)
  options = default_options.merge options
  # move to the starting point and traverse the xml
  filtered = options[:filter].inject(xml) { |hash, key| hash[key] }
  traverse = NestedHash[filtered].map_values_with_route do |route, value|
    # skip attributes?
    next if !options[:attributes] && route.any? { |r| r =~ /@/ }
    # prohibited type?
    next if options[:prohibited_types].any? { |type| value.is_a?(type) }
    # extract data from lists
    value = ListHeuristics.new(value).to_variable_hash if value.is_a?(Array)
    [route, value]
  end.compact
  # create variable:value mapping
  # need the second iteration in case of list data
  parsed = NestedHash[traverse].map_values_with_route do |route, value|
    key = make_key(route, options)
    [key, value]
  end
  NestedHash[parsed]
end