From 78c8cd132394cbd05171a72ee011814d8a1f009e Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Thu, 28 Aug 2014 23:05:12 +0200 Subject: [PATCH] Support for the XPath "div" operator. --- lib/oga/xpath/evaluator.rb | 16 +++++++++ .../oga/xpath/evaluator/operators/div_spec.rb | 34 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 spec/oga/xpath/evaluator/operators/div_spec.rb diff --git a/lib/oga/xpath/evaluator.rb b/lib/oga/xpath/evaluator.rb index ce491dc..6a46ddf 100644 --- a/lib/oga/xpath/evaluator.rb +++ b/lib/oga/xpath/evaluator.rb @@ -642,6 +642,22 @@ module Oga return on_call_number(context, left) + on_call_number(context, right) end + ## + # Processes the `div` operator. + # + # This operator converts the left and right expressions to numbers and + # divides the left number with the right number. + # + # @param [Oga::XPath::Node] ast_node + # @param [Oga::XML::NodeSet] context + # @return [Float] + # + def on_div(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/div_spec.rb b/spec/oga/xpath/evaluator/operators/div_spec.rb new file mode 100644 index 0000000..91d2d07 --- /dev/null +++ b/spec/oga/xpath/evaluator/operators/div_spec.rb @@ -0,0 +1,34 @@ +require 'spec_helper' + +describe Oga::XPath::Evaluator do + context 'div operator' do + before do + @document = parse('12') + @evaluator = described_class.new(@document) + end + + example 'divide two numbers' do + @evaluator.evaluate('1 div 2').should == 0.5 + end + + example 'divide a number and a string' do + @evaluator.evaluate('1 div "2"').should == 0.5 + end + + example 'divide two strings' do + @evaluator.evaluate('"1" div "2"').should == 0.5 + end + + example 'divide a number and a node set' do + @evaluator.evaluate('root/a div 2').should == 0.5 + end + + example 'divide two node sets' do + @evaluator.evaluate('root/a div root/b').should == 0.5 + end + + example 'return NaN when trying to divide invalid values' do + @evaluator.evaluate('"" div 1').should be_nan + end + end +end