Support for the XPath count() function.

This commit is contained in:
Yorick Peterse 2014-08-20 10:16:06 +02:00
parent 709fa365e0
commit d351bc26cc
3 changed files with 88 additions and 1 deletions

View File

@ -601,7 +601,7 @@ module Oga
# @return [Oga::XML::NodeSet] # @return [Oga::XML::NodeSet]
# #
def on_call(ast_node, context) def on_call(ast_node, context)
name, args = *ast_node name, *args = *ast_node
handler = name.gsub('-', '_') handler = name.gsub('-', '_')
@ -633,6 +633,36 @@ module Oga
return index.to_f return index.to_f
end end
##
# Processes the `count()` function call. This function counts the amount
# of nodes in `expression` and returns the result as a float.
#
# @param [Oga::XML::NodeSet] context
# @param [Oga::XPath::Node] expression
# @return [Float]
#
def on_call_count(context, expression)
retval = process(expression, context)
unless retval.is_a?(XML::NodeSet)
raise TypeError, 'count() can only operate on NodeSet instances'
end
return retval.length.to_f
end
##
# Processes an `(int)` node. This method simply returns the value as a
# Float.
#
# @param [Oga::XPath::Node] ast_node
# @param [Oga::XML::NodeSet] context
# @return [Float]
#
def on_int(ast_node, context)
return ast_node.children[0].to_f
end
## ##
# Returns a node set containing all the child nodes of the given set of # Returns a node set containing all the child nodes of the given set of
# nodes. # nodes.

View File

@ -0,0 +1,38 @@
require 'spec_helper'
describe Oga::XPath::Evaluator do
context 'count() function' do
before do
@document = parse('<root><a><b></b></a><a></a></root>')
@evaluator = described_class.new(@document)
end
example 'return the amount of nodes as a Float' do
@evaluator.evaluate('count(root)').is_a?(Float).should == true
end
example 'count the amount of <root> nodes' do
@evaluator.evaluate('count(root)').should == 1
end
example 'count the amount of <a> nodes' do
@evaluator.evaluate('count(root/a)').should == 2
end
example 'count the amount of <b> nodes' do
@evaluator.evaluate('count(root/a/b)').should == 1
end
example 'raise ArgumentError if no arguments are given' do
block = lambda { @evaluator.evaluate('count()') }
block.should raise_error(ArgumentError)
end
example 'raise TypeError if the argument is not a NodeSet' do
block = lambda { @evaluator.evaluate('count(1)') }
block.should raise_error(TypeError)
end
end
end

View File

@ -0,0 +1,19 @@
require 'spec_helper'
describe Oga::XPath::Evaluator do
context 'integer types' do
before do
document = parse('<a></a>')
evaluator = described_class.new(document)
@number = evaluator.evaluate('1')
end
example 'return literal integers' do
@number.should == 1
end
example 'return integers as floats' do
@number.is_a?(Float).should == true
end
end
end