Expanded supported input for Conversion.to_float

This extends XPath::Conversion.to_float so it can also convert NodeSet
and Node instances.
This commit is contained in:
Yorick Peterse 2015-07-28 09:31:01 +02:00
parent 8a82cc3593
commit 376d016acd
2 changed files with 48 additions and 7 deletions

View File

@ -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

View File

@ -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