From a70645fb89d132693051c12c909d30eceda86f25 Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Fri, 29 Aug 2014 09:41:17 +0200 Subject: [PATCH] Support for the XPath sub/- operator. --- lib/oga/xpath/evaluator.rb | 16 +++++++++ .../xpath/evaluator/operators/sub_operator.rb | 34 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 spec/oga/xpath/evaluator/operators/sub_operator.rb diff --git a/lib/oga/xpath/evaluator.rb b/lib/oga/xpath/evaluator.rb index 3c4e98d..83f5f22 100644 --- a/lib/oga/xpath/evaluator.rb +++ b/lib/oga/xpath/evaluator.rb @@ -690,6 +690,22 @@ module Oga return on_call_number(context, left) * on_call_number(context, right) end + ## + # Processes the `-` operator. + # + # This operator converts the left and right expressions to numbers and + # subtracts the right number of the left number. + # + # @param [Oga::XPath::Node] ast_node + # @param [Oga::XML::NodeSet] context + # @return [Float] + # + def on_sub(ast_node, context) + left, right = *ast_node + + return on_call_number(context, left) - on_call_number(context, right) + end + ## # Delegates function calls to specific handlers. # diff --git a/spec/oga/xpath/evaluator/operators/sub_operator.rb b/spec/oga/xpath/evaluator/operators/sub_operator.rb new file mode 100644 index 0000000..bc2d602 --- /dev/null +++ b/spec/oga/xpath/evaluator/operators/sub_operator.rb @@ -0,0 +1,34 @@ +require 'spec_helper' + +describe Oga::XPath::Evaluator do + context 'subtraction operator' do + before do + @document = parse('23') + @evaluator = described_class.new(@document) + end + + example 'subtract two numbers' do + @evaluator.evaluate('2 - 3').should == -1.0 + end + + example 'subtract a number and a string' do + @evaluator.evaluate('2 - "3"').should == -1.0 + end + + example 'subtract two strings' do + @evaluator.evaluate('"2" - "3"').should == -1.0 + end + + example 'subtract a node set and a number' do + @evaluator.evaluate('root/a - 3').should == -1.0 + end + + example 'subtract two node sets' do + @evaluator.evaluate('root/a - root/b').should == -1.0 + end + + example 'return NaN when trying to subtract invalid values' do + @evaluator.evaluate('"" - 1').should be_nan + end + end +end