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_or_options = nil) ⇒ XmlFile

Returns a new instance of XmlFile.



6
7
8
9
10
11
12
13
# File 'lib/dynport_tools/xml_file.rb', line 6

def initialize(path_or_options = nil)
  if path_or_options.is_a?(Hash)
    self.path = path_or_options[:path].to_s if path_or_options[:path].to_s
    self.content = path_or_options[:content]
  elsif !path_or_options.nil?
    self.path = path_or_options.to_s
  end
end

Instance Attribute Details

#contentObject

Returns the value of attribute content.



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

def content
  @content
end

#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



19
20
21
# File 'lib/dynport_tools/xml_file.rb', line 19

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

#flatten_hash(in_hash) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/dynport_tools/xml_file.rb', line 49

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



39
40
41
42
43
44
45
46
47
# File 'lib/dynport_tools/xml_file.rb', line 39

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



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

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

#parse_node(node) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/dynport_tools/xml_file.rb', line 23

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