Class: XmlNodeStream::Selector::Matcher
- Inherits:
-
Object
- Object
- XmlNodeStream::Selector::Matcher
- Defined in:
- lib/xml_node_stream/selector.rb
Overview
Match a partial path to a node.
Instance Method Summary collapse
-
#initialize(path) ⇒ Matcher
constructor
Create a new Matcher.
-
#select(context_nodes) ⇒ Array<Node>
Select all nodes that match a partial path.
Constructor Details
#initialize(path) ⇒ Matcher
Create a new Matcher.
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/xml_node_stream/selector.rb', line 142 def initialize(path) @path = path @text = (path == "text()") @extractor = case path when "text()" lambda { |node| node.value unless node.value.nil? || node.value.empty? } when "%" lambda { |node| node.descendants } when "*" lambda { |node| node.children } when "." lambda { |node| node } when ".." lambda { |node| node.parent || [] } when "" lambda { |node| root = Node.new(nil) root.children << node.root root } when /^%(.+)$/ # descendants with name filter: %name name = $1 lambda { |node| node.descendants.select { |d| d.name == name } } else lambda { |node| node.children.select { |child| child.name == @path } } end end |
Instance Method Details
#select(context_nodes) ⇒ Array<Node>
Select all nodes that match a partial path.
174 175 176 177 178 |
# File 'lib/xml_node_stream/selector.rb', line 174 def select(context_nodes) results = context_nodes.collect { |node| @extractor.call(node) if node.is_a?(Node) }.flatten.compact # Text values from different nodes can legitimately be equal, so only dedupe nodes. @text ? results : results.uniq end |