| 1 |
Index: test/core_ext/bigdecimal.rb |
|---|
| 2 |
=================================================================== |
|---|
| 3 |
--- test/core_ext/bigdecimal.rb (revision 0) |
|---|
| 4 |
+++ test/core_ext/bigdecimal.rb (revision 0) |
|---|
| 5 |
@@ -0,0 +1,9 @@ |
|---|
| 6 |
+require 'abstract_unit' |
|---|
| 7 |
+ |
|---|
| 8 |
+class BigDecimalTest < Test::Unit::TestCase |
|---|
| 9 |
+ def test_to_yaml |
|---|
| 10 |
+ assert_equal("--- 100000.30020320320000000000000000000000000000001\n", BigDecimal.new('100000.30020320320000000000000000000000000000001').to_yaml) |
|---|
| 11 |
+ assert_equal("--- .Inf\n", BigDecimal.new('Infinity').to_yaml) |
|---|
| 12 |
+ assert_equal("--- .NaN\n", BigDecimal.new('NaN').to_yaml) |
|---|
| 13 |
+ end |
|---|
| 14 |
+end |
|---|
| 15 |
\ No newline at end of file |
|---|
| 16 |
Index: lib/active_support/core_ext/bigdecimal/conversions.rb |
|---|
| 17 |
=================================================================== |
|---|
| 18 |
--- lib/active_support/core_ext/bigdecimal/conversions.rb (revision 8858) |
|---|
| 19 |
+++ lib/active_support/core_ext/bigdecimal/conversions.rb (working copy) |
|---|
| 20 |
@@ -1,3 +1,5 @@ |
|---|
| 21 |
+require 'yaml' |
|---|
| 22 |
+ |
|---|
| 23 |
class BigDecimal #:nodoc: |
|---|
| 24 |
alias :_original_to_s :to_s |
|---|
| 25 |
def to_s(format="F") |
|---|
| 26 |
@@ -3,3 +5,23 @@ |
|---|
| 27 |
_original_to_s(format) |
|---|
| 28 |
end |
|---|
| 29 |
+ |
|---|
| 30 |
+ def to_yaml( opts = {} ) |
|---|
| 31 |
+ YAML::quick_emit( nil, opts ) do |out| |
|---|
| 32 |
+ # This emits the number without any scientific notation. |
|---|
| 33 |
+ # I prefer it to using self.to_f.to_s, which would lose precision. |
|---|
| 34 |
+ # |
|---|
| 35 |
+ # Note that YAML allows that when reconsituting floats |
|---|
| 36 |
+ # to native types, some precision may get lost. |
|---|
| 37 |
+ # There is no full precision real YAML tag that I am aware of. |
|---|
| 38 |
+ str = self.to_s |
|---|
| 39 |
+ if str == "Infinity" |
|---|
| 40 |
+ str = ".Inf" |
|---|
| 41 |
+ elsif str == "-Infinity" |
|---|
| 42 |
+ str = "-.Inf" |
|---|
| 43 |
+ elsif str == "NaN" |
|---|
| 44 |
+ str = ".NaN" |
|---|
| 45 |
+ end |
|---|
| 46 |
+ out.scalar( "tag:yaml.org,2002:float", str, :plain ) |
|---|
| 47 |
+ end |
|---|
| 48 |
+ end |
|---|
| 49 |
end |
|---|