Support for the XPath "div" operator.

This commit is contained in:
Yorick Peterse 2014-08-28 23:05:12 +02:00
parent ced7f739fc
commit 78c8cd1323
2 changed files with 50 additions and 0 deletions

View File

@ -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.
#

View File

@ -0,0 +1,34 @@
require 'spec_helper'
describe Oga::XPath::Evaluator do
context 'div operator' do
before do
@document = parse('<root><a>1</a><b>2</b></root>')
@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