Class: XmlNodeStream::Selector::Matcher

Inherits:
Object
  • Object
show all
Defined in:
lib/xml_node_stream/selector.rb

Overview

Match a partial path to a node.

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Matcher

Create a new Matcher.

Parameters:

  • path (String)

    the path pattern to match



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.

Parameters:

  • context_nodes (Array<Node>)

    the nodes to select from

Returns:

  • (Array<Node>)

    the matching nodes



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