Support for the XPath "add" / "+" operator.

This commit is contained in:
Yorick Peterse 2014-08-28 21:18:09 +02:00
parent 4fa40b58cf
commit ced7f739fc
2 changed files with 50 additions and 0 deletions

View File

@ -626,6 +626,22 @@ module Oga
return on_call_boolean(context, left) || on_call_boolean(context, right)
end
##
# Processes the `+` operator.
#
# This operator converts the left and right expressions to numbers and
# adds them together.
#
# @param [Oga::XPath::Node] ast_node
# @param [Oga::XML::NodeSet] context
# @return [Float]
#
def on_add(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 'add operator' do
before do
@document = parse('<root><a>1</a><b>2</b></root>')
@evaluator = described_class.new(@document)
end
example 'add two numbers' do
@evaluator.evaluate('1 + 2').should == 3.0
end
example 'add a number and a string' do
@evaluator.evaluate('1 + "2"').should == 3.0
end
example 'add two strings' do
@evaluator.evaluate('"1" + "2"').should == 3.0
end
example 'add a number and a node set' do
@evaluator.evaluate('root/a + 2').should == 3.0
end
example 'add two node sets' do
@evaluator.evaluate('root/a + root/b').should == 3.0
end
example 'return NaN when trying to add invalid values' do
@evaluator.evaluate('"" + 1').should be_nan
end
end
end