Class: Nokogiri::XML::Node
- Inherits:
-
Object
- Object
- Nokogiri::XML::Node
- Defined in:
- lib/data_collector/ext/nokogiri.rb
Overview
Mix-in of the Nokogiri XML Node Class that implements methods to convert nodes to a hash. Author: Mario “Kuroir” Ricalde (kuroir.com)
Instance Method Summary collapse
-
#collect_attributes ⇒ Object
Collect Attributes of a given node.
-
#collect_children ⇒ Object
Priest method.
-
#collect_nodes ⇒ Object
Recursive method to collect nodes.
-
#to_hash(selector = 'body > *') ⇒ Object
Convert a selected node to a Hash.
Instance Method Details
#collect_attributes ⇒ Object
Collect Attributes of a given node.
26 27 28 29 30 |
# File 'lib/data_collector/ext/nokogiri.rb', line 26 def collect_attributes output = {} self.attributes.each { |name, value| output = output.merge({ name.to_sym => value.to_s.split(/\s+/) }) } output end |
#collect_children ⇒ Object
Priest method.
33 34 35 |
# File 'lib/data_collector/ext/nokogiri.rb', line 33 def collect_children self.element_children.collect { |child| child.collect_nodes } || [] end |
#collect_nodes ⇒ Object
Recursive method to collect nodes. We add the children symbol always to keep the array structure constant.
21 22 23 |
# File 'lib/data_collector/ext/nokogiri.rb', line 21 def collect_nodes { self.name.to_sym => self.collect_attributes.merge({:children => collect_children }) } end |
#to_hash(selector = 'body > *') ⇒ Object
Convert a selected node to a Hash. It accepts a CSS3 Selector as an attribute. Returns the hash.
10 11 12 13 14 15 16 17 |
# File 'lib/data_collector/ext/nokogiri.rb', line 10 def to_hash(selector = 'body > *') hash = [] self.css(selector).each do |node| hash << node.collect_nodes end # Return the hash hash.map{|m| m.is_a?(Hash) ? m.with_indifferent_access : m} end |