From fbf3ae6e36477656ba9352abc6e9208734125199 Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Wed, 3 Sep 2014 23:51:53 +0200 Subject: [PATCH] Manually increment XPath indexes. This ensures that the index is only incremented for elements that match a node test. --- lib/oga/xpath/evaluator.rb | 11 ++++++----- spec/oga/xpath/evaluator/predicates_spec.rb | 22 +++++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) create mode 100644 spec/oga/xpath/evaluator/predicates_spec.rb diff --git a/lib/oga/xpath/evaluator.rb b/lib/oga/xpath/evaluator.rb index e63ecaa..de43045 100644 --- a/lib/oga/xpath/evaluator.rb +++ b/lib/oga/xpath/evaluator.rb @@ -169,15 +169,14 @@ module Oga # @return [Oga::XML::NodeSet] # def on_test(ast_node, context) - nodes = XML::NodeSet.new - predicate = ast_node.children[2] + nodes = XML::NodeSet.new + predicate = ast_node.children[2] + xpath_index = 1 - context.each_with_index do |xml_node, index| + context.each do |xml_node| next unless node_matches?(xml_node, ast_node) if predicate - xpath_index = index + 1 - retval = with_node_set(context) do process(predicate, XML::NodeSet.new([xml_node])) end @@ -197,6 +196,8 @@ module Oga else nodes << xml_node end + + xpath_index += 1 end return nodes diff --git a/spec/oga/xpath/evaluator/predicates_spec.rb b/spec/oga/xpath/evaluator/predicates_spec.rb new file mode 100644 index 0000000..7e67cae --- /dev/null +++ b/spec/oga/xpath/evaluator/predicates_spec.rb @@ -0,0 +1,22 @@ +require 'spec_helper' + +describe Oga::XPath::Evaluator do + context 'predicates' do + before do + @document = parse('1020') + @evaluator = described_class.new(@document) + end + + context 'using predicate indexes' do + before do + @set = @evaluator.evaluate('root/b[2]') + end + + it_behaves_like :node_set, :length => 1 + + example 'return the second node' do + @set[0].should == @document.children[0].children[-1] + end + end + end +end