From 543112dcdcbfd5efe30c01ff13cb1129db74f80e Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Thu, 28 Aug 2014 00:00:25 +0200 Subject: [PATCH] Support for the XPath round() function. --- lib/oga/xpath/evaluator.rb | 16 +++++++++++ spec/oga/xpath/evaluator/calls/round_spec.rb | 30 ++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 spec/oga/xpath/evaluator/calls/round_spec.rb diff --git a/lib/oga/xpath/evaluator.rb b/lib/oga/xpath/evaluator.rb index 0d13f7f..e840b43 100644 --- a/lib/oga/xpath/evaluator.rb +++ b/lib/oga/xpath/evaluator.rb @@ -1216,6 +1216,22 @@ module Oga return number.nan? ? number : number.ceil.to_f end + ## + # Processes the `round()` function call. + # + # This function call rounds the 1st argument to the closest integer number + # and then returns that number as a float. + # + # @param [Oga::XML::NodeSet] context + # @param [Oga::XPath::Node] expression + # @return [Float] + # + def on_call_round(context, expression) + number = on_call_number(context, expression) + + return number.nan? ? number : number.round.to_f + end + ## # Processes an `(int)` node. # diff --git a/spec/oga/xpath/evaluator/calls/round_spec.rb b/spec/oga/xpath/evaluator/calls/round_spec.rb new file mode 100644 index 0000000..2d0ea6c --- /dev/null +++ b/spec/oga/xpath/evaluator/calls/round_spec.rb @@ -0,0 +1,30 @@ +require 'spec_helper' + +describe Oga::XPath::Evaluator do + context 'round() function' do + before do + @document = parse('10.123') + @evaluator = described_class.new(@document) + end + + example 'return the rounded value of a literal number' do + @evaluator.evaluate('round(10.123)').should == 10.0 + end + + example 'return the rounded value of a literal string' do + @evaluator.evaluate('round("10.123")').should == 10.0 + end + + example 'return the rounded value of a node set' do + @evaluator.evaluate('round(root)').should == 10.0 + end + + example 'return NaN for empty node sets' do + @evaluator.evaluate('round(foo)').should be_nan + end + + example 'return NaN for an empty literal string' do + @evaluator.evaluate('round("")').should be_nan + end + end +end