Class: DynportTools::XmlFile

Inherits:
Object
  • Object
show all
Defined in:
lib/dynport_tools/xml_file.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ XmlFile

Returns a new instance of XmlFile.



6
7
8
# File 'lib/dynport_tools/xml_file.rb', line 6

def initialize(path)
  self.path = path.to_s
end

Instance Attribute Details

#pathObject

Returns the value of attribute path.



4
5
6
# File 'lib/dynport_tools/xml_file.rb', line 4

def path
  @path
end

Instance Method Details

#docObject



14
15
16
# File 'lib/dynport_tools/xml_file.rb', line 14

def doc
  @doc ||= Nokogiri::XML(File.open(path))
end

#flatten_hash(in_hash) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/dynport_tools/xml_file.rb', line 44

def flatten_hash(in_hash)
  in_hash.inject({}) do |hash, (key, arr_of_value)|
    if arr_of_value.is_a?(Array)
      if arr_of_value.length == 0
        hash[key] = nil
      elsif arr_of_value.length == 1
        hash[key] = arr_of_value.first
      else
        hash[key] = arr_of_value
      end
    else
      hash[key] = arr_of_value
    end
    hash
  end
end

#key_for_node(node) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/dynport_tools/xml_file.rb', line 34

def key_for_node(node)
  if node.attributes.any?
    node.attributes.inject({ :name => node.name }) do |hash, (key, value)|
      hash.merge!(key => value.value)
    end
  else
    node.name
  end
end

#nodes_hashObject



10
11
12
# File 'lib/dynport_tools/xml_file.rb', line 10

def nodes_hash
  { key_for_node(doc.root) => parse_node(doc.root) }
end

#parse_node(node) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/dynport_tools/xml_file.rb', line 18

def parse_node(node)
  child_elements = node.children.select { |n| n.is_a?(Nokogiri::XML::Element) }
  value = if child_elements.any?
    flatten_hash(
      child_elements.inject({}) do |hash, el|
        hash[key_for_node(el)] ||= Array.new
        hash[key_for_node(el)] << parse_node(el)
        hash
      end
    )
  else
    txt = node.inner_text.strip
    txt.length == 0 ? nil : txt
  end
end