From 376d016acd884f180f90d10cef7c504ed5e4f6b9 Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Tue, 28 Jul 2015 09:31:01 +0200 Subject: [PATCH] Expanded supported input for Conversion.to_float This extends XPath::Conversion.to_float so it can also convert NodeSet and Node instances. --- lib/oga/xpath/conversion.rb | 23 +++++++++++++++++++--- spec/oga/xpath/conversion_spec.rb | 32 +++++++++++++++++++++++++++---- 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/lib/oga/xpath/conversion.rb b/lib/oga/xpath/conversion.rb index b66168f..cd7477b 100644 --- a/lib/oga/xpath/conversion.rb +++ b/lib/oga/xpath/conversion.rb @@ -43,8 +43,7 @@ module Oga end if value.is_a?(XML::NodeSet) - first = value.first - value = first.respond_to?(:text) ? first.text : '' + value = first_node_text(value) end if value.respond_to?(:text) @@ -56,7 +55,19 @@ module Oga # @return [Float] def self.to_float(value) - Float(value) rescue Float::NAN + if value.is_a?(XML::NodeSet) + value = first_node_text(value) + end + + if value.respond_to?(:text) + value = value.text + end + + if value.is_a?(String) + value = Float(value) rescue Float::NAN + end + + value end # @return [TrueClass|FalseClass] @@ -78,6 +89,12 @@ module Oga def self.boolean?(value) value.is_a?(TrueClass) || value.is_a?(FalseClass) end + + # @param [Oga::XML::NodeSet] set + # @return [String] + def self.first_node_text(set) + set[0].respond_to?(:text) ? set[0].text : '' + end end # Conversion end # XPath end # Oga diff --git a/spec/oga/xpath/conversion_spec.rb b/spec/oga/xpath/conversion_spec.rb index c8d79c8..66dfa5a 100644 --- a/spec/oga/xpath/conversion_spec.rb +++ b/spec/oga/xpath/conversion_spec.rb @@ -125,12 +125,36 @@ describe Oga::XPath::Conversion do end describe 'to_float' do - it 'returns a Float for a valid value' do - described_class.to_float('10.5').should == 10.5 + describe 'using a Float' do + it 'returns the input Float' do + described_class.to_float(10.5).should == 10.5 + end end - it 'returns Float::NAN for an invalid value' do - described_class.to_float('foo').nan?.should == true + describe 'using a String' do + it 'returns a Float for a valid value' do + described_class.to_float('10.5').should == 10.5 + end + + it 'returns Float::NAN for an invalid value' do + described_class.to_float('foo').nan?.should == true + end + end + + describe 'using a NodeSet' do + it 'returns a Float using the text of the first node' do + set = node_set(Oga::XML::Text.new(:text => '10.5')) + + described_class.to_float(set).should == 10.5 + end + end + + describe 'using an Node' do + it 'returns a Float using the text of the node' do + node = Oga::XML::Text.new(:text => '10.5') + + described_class.to_float(node).should == 10.5 + end end end