From 33ce8650bac29190dde937b1b7d3e21fd06926e7 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Sat, 17 Dec 2011 19:45:07 -0800 Subject: [PATCH] * ext/psych/lib/psych/visitors/to_ruby.rb: BigDecimals can be restored from YAML. * ext/psych/lib/psych/visitors/yaml_tree.rb: BigDecimals can be dumped to YAML. * test/psych/test_numeric.rb: tests for BigDecimal serialization Fixes #31 --- CHANGELOG.rdoc | 8 ++++++++ lib/psych/visitors/to_ruby.rb | 3 +++ lib/psych/visitors/yaml_tree.rb | 4 ++++ test/psych/test_numeric.rb | 11 +++++++++++ 4 files changed, 26 insertions(+) diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc index 14ef3b57..bd9a3fcc 100644 --- a/CHANGELOG.rdoc +++ b/CHANGELOG.rdoc @@ -1,3 +1,11 @@ +Sun Dec 18 12:42:48 2011 Aaron Patterson + + * ext/psych/lib/psych/visitors/to_ruby.rb: BigDecimals can be restored + from YAML. + * ext/psych/lib/psych/visitors/yaml_tree.rb: BigDecimals can be dumped + to YAML. + * test/psych/test_numeric.rb: tests for BigDecimal serialization + Sun Dec 18 12:03:13 2011 Aaron Patterson * ext/psych/lib/psych/scalar_scanner.rb: Strings that look like dates diff --git a/lib/psych/visitors/to_ruby.rb b/lib/psych/visitors/to_ruby.rb index 4267f4d0..bf48f9d0 100644 --- a/lib/psych/visitors/to_ruby.rb +++ b/lib/psych/visitors/to_ruby.rb @@ -52,6 +52,9 @@ def deserialize o o.value.unpack('m').first when '!str', 'tag:yaml.org,2002:str' o.value + when '!ruby/object:BigDecimal' + require 'bigdecimal' + BigDecimal._load o.value when "!ruby/object:DateTime" require 'date' @ss.parse_time(o.value).to_datetime diff --git a/lib/psych/visitors/yaml_tree.rb b/lib/psych/visitors/yaml_tree.rb index 523ad776..f3739660 100644 --- a/lib/psych/visitors/yaml_tree.rb +++ b/lib/psych/visitors/yaml_tree.rb @@ -214,6 +214,10 @@ def visit_Float o end end + def visit_BigDecimal o + @emitter.scalar o._dump, nil, '!ruby/object:BigDecimal', false, false, Nodes::Scalar::ANY + end + def binary? string string.encoding == Encoding::ASCII_8BIT || string.index("\x00") || diff --git a/test/psych/test_numeric.rb b/test/psych/test_numeric.rb index 9adb058a..bae723ac 100644 --- a/test/psych/test_numeric.rb +++ b/test/psych/test_numeric.rb @@ -1,4 +1,5 @@ require 'psych/helper' +require 'bigdecimal' module Psych ### @@ -10,5 +11,15 @@ def test_non_float_with_0 str = Psych.load('--- 090') assert_equal '090', str end + + def test_big_decimal_tag + decimal = BigDecimal("12.34") + assert_match "!ruby/object:BigDecimal", Psych.dump(decimal) + end + + def test_big_decimal_round_trip + decimal = BigDecimal("12.34") + assert_cycle decimal + end end end