From 5382891106e7fa4f6519d350d035614812384191 Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Mon, 25 Aug 2014 23:13:03 +0200 Subject: [PATCH] Support for the XPath number() function. --- lib/oga/xpath/evaluator.rb | 20 +++++++++++ spec/oga/xpath/evaluator/calls/number_spec.rb | 34 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 spec/oga/xpath/evaluator/calls/number_spec.rb diff --git a/lib/oga/xpath/evaluator.rb b/lib/oga/xpath/evaluator.rb index fcc5643..4debd4d 100644 --- a/lib/oga/xpath/evaluator.rb +++ b/lib/oga/xpath/evaluator.rb @@ -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. # diff --git a/spec/oga/xpath/evaluator/calls/number_spec.rb b/spec/oga/xpath/evaluator/calls/number_spec.rb new file mode 100644 index 0000000..7f856e1 --- /dev/null +++ b/spec/oga/xpath/evaluator/calls/number_spec.rb @@ -0,0 +1,34 @@ +require 'spec_helper' + +describe Oga::XPath::Evaluator do + context 'number() function' do + before do + @document = parse('1010.5') + @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