Support for the XPath number() function.
This commit is contained in:
parent
ba058627f2
commit
5382891106
|
@ -788,6 +788,26 @@ module Oga
|
|||
end
|
||||
end
|
||||
|
||||
##
|
||||
# Evaluates the `number()` function call.
|
||||
#
|
||||
# This function call converts its first argument *or* the current context
|
||||
# node to a number, similar to the `string()` function.
|
||||
#
|
||||
# @example
|
||||
# number("10") # => 10.0
|
||||
#
|
||||
# @see [#on_call_string]
|
||||
# @param [Oga::XML::NodeSet] context
|
||||
# @param [Oga::XPath::Node] expression
|
||||
# @return [Float]
|
||||
#
|
||||
def on_call_number(context, expression = nil)
|
||||
str_val = on_call_string(context, expression)
|
||||
|
||||
return Float(str_val) rescue Float::NAN
|
||||
end
|
||||
|
||||
##
|
||||
# Processes the `concat()` function call.
|
||||
#
|
||||
|
|
|
@ -0,0 +1,34 @@
|
|||
require 'spec_helper'
|
||||
|
||||
describe Oga::XPath::Evaluator do
|
||||
context 'number() function' do
|
||||
before do
|
||||
@document = parse('<root><a>10</a><b>10.5</b><!--10--></root>')
|
||||
@evaluator = described_class.new(@document)
|
||||
end
|
||||
|
||||
example 'convert a literal string to a number' do
|
||||
@evaluator.evaluate('number("10")').should == 10.0
|
||||
end
|
||||
|
||||
example 'convert a literal string with deciamsl to a number' do
|
||||
@evaluator.evaluate('number("10.5")').should == 10.5
|
||||
end
|
||||
|
||||
example 'convert a node set to a number' do
|
||||
@evaluator.evaluate('number(root/a)').should == 10.0
|
||||
end
|
||||
|
||||
example 'convert a node set with decimals to a number' do
|
||||
@evaluator.evaluate('number(root/b)').should == 10.5
|
||||
end
|
||||
|
||||
example 'convert a comment to a number' do
|
||||
@evaluator.evaluate('number(root/comment())').should == 10.0
|
||||
end
|
||||
|
||||
example 'return NaN for values that can not be converted to floats' do
|
||||
@evaluator.evaluate('number("a")').should be_nan
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in New Issue