Class: Nokogiri::XML::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/nfe_reader/helpers/nokogiri_hash.rb

Instance Method Summary collapse

Instance Method Details

#attributes_in_hash(node_attributes = {}) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/nfe_reader/helpers/nokogiri_hash.rb', line 25

def attributes_in_hash(node_attributes = {})
  attributes.keys.each do |key|
    name = attributes[key].name.to_sym
    node_attributes[name] = attributes[key].value
  end

  node_attributes
end

#children_in_hash(result_hash = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/nfe_reader/helpers/nokogiri_hash.rb', line 34

def children_in_hash(result_hash = {})
  children.each do |child|
    result = child.collect_nodes
    name = child.name.to_sym

    if child.name == "text"
      unless child.next_sibling || child.previous_sibling
        return result
      end
    elsif child.cdata?
      return child.text
    elsif result_hash[name]
      if result_hash[name].is_a?(Object::Array)
        result_hash[name] << result
      else
        result_hash[name] = [result_hash[name]] << result
      end
    else
      if result.class == Hash && result.empty?
        result_hash[name] = nil
      else
        result_hash[name] = result
      end
    end
  end

  result_hash
end

#collect_nodes(result_hash = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/nfe_reader/helpers/nokogiri_hash.rb', line 8

def collect_nodes(result_hash = {})
  if element?
    hash_attributes = attributes_in_hash
    hash_children = children_in_hash

    if hash_attributes != {}
      result_hash = hash_attributes.merge(hash_children)
    else
      result_hash = hash_children
    end

    result_hash
  else
    content.to_s
  end 
end

#to_hashObject



2
3
4
5
6
# File 'lib/nfe_reader/helpers/nokogiri_hash.rb', line 2

def to_hash
  return { root.name.to_sym => root.collect_nodes }
rescue Exception => e
  { :error => e.to_s }
end