From f29a01953665c3f043cb469f0f98524b9991f718 Mon Sep 17 00:00:00 2001 From: Lars Kuhnt Date: Wed, 21 Jan 2015 15:11:59 +0100 Subject: [PATCH] fixed typecast of values, as i.e. a value of 012 was parsed to 10 --- lib/inifile.rb | 13 ++++++++++--- test/data/typecast.ini | 7 +++++++ test/test_inifile.rb | 16 ++++++++++++++++ 3 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 test/data/typecast.ini diff --git a/lib/inifile.rb b/lib/inifile.rb index fbcfb0e..7422eed 100644 --- a/lib/inifile.rb +++ b/lib/inifile.rb @@ -596,10 +596,17 @@ def typecast( value ) when %r/\Afalse\z/i; false when %r/\A\s*\z/i; nil else - Integer(value) rescue \ - Float(value) rescue \ - unescape_value(value) + stripped_value = value.strip + if stripped_value =~ /^\d*\.\d+$/ + Float(stripped_value) + elsif stripped_value =~ /^[^0]\d*$/ + Integer(stripped_value) + else + unescape_value(value) + end end + rescue + unescape_value(value) end # Unescape special characters found in the value string. This will convert diff --git a/test/data/typecast.ini b/test/data/typecast.ini new file mode 100644 index 0000000..3468066 --- /dev/null +++ b/test/data/typecast.ini @@ -0,0 +1,7 @@ +[section_one] +int1 = 146 +float1 = 0.35 +float2 = .634 +float3 = 234.646 +string1 = 00342 +string2 = 345. diff --git a/test/test_inifile.rb b/test/test_inifile.rb index 2026065..0daa356 100644 --- a/test/test_inifile.rb +++ b/test/test_inifile.rb @@ -557,5 +557,21 @@ def test_empty_comment_string assert_equal 3, ini_file['section_one']['one'] assert_equal 5, ini_file['section_five']['five'] end + + def test_integer_typecast + ini_file = IniFile.load('test/data/typecast.ini') + assert_equal 146, ini_file['section_one']['int1'] + assert_equal "00342", ini_file['section_one']['string1'] + end + + def test_float_typecast + ini_file = IniFile.load('test/data/typecast.ini') + assert_equal 0.35, ini_file['section_one']['float1'] + assert_equal 0.634, ini_file['section_one']['float2'] + assert_equal 234.646, ini_file['section_one']['float3'] + assert_equal "345.", ini_file['section_one']['string2'] + end + + end