Support for the XPath sum() function.

This commit is contained in:
Yorick Peterse 2014-08-27 23:05:04 +02:00
parent 585b3535b2
commit 30a5d01ebd
2 changed files with 49 additions and 0 deletions

View File

@ -1132,6 +1132,36 @@ module Oga
return false return false
end end
##
# Processes the `sum()` function call.
#
# This function call takes a node set, converts each node to a number and
# then sums the values.
#
# As an example, take the following XML:
#
# <root>
# <a>1</a>
# <b>2</b>
# </root>
#
# Using the expression `sum(root/*)` the return value would be `3.0`.
#
# @param [Oga::XML::NodeSet] context
# @param [Oga::XPath::Node] expression
# @return [Float]
#
def on_call_sum(context, expression)
nodes = process(expression, context)
sum = 0.0
nodes.each do |node|
sum += node.text.to_f
end
return sum
end
## ##
# Processes an `(int)` node. # Processes an `(int)` node.
# #

View File

@ -0,0 +1,19 @@
require 'spec_helper'
describe Oga::XPath::Evaluator do
context 'sum() spec' do
before do
@document = parse('<root><a>1</a><b>2</b></root>')
@evaluator = described_class.new(@document)
end
example 'return the sum of the <root> node' do
# The test of <root> is "12", which is then converted to a number.
@evaluator.evaluate('sum(root)').should == 12.0
end
example 'return the sum of the child nodes of the <root> node' do
@evaluator.evaluate('sum(root/*)').should == 3.0
end
end
end