Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Changeset 8877

Show
Ignore:
Timestamp:
02/15/08 23:33:43 (7 months ago)
Author:
nzkoz
Message:

Serialize BigDecimals as Floats when using to_yaml. Closes #8746 [ernesto.jimenez]

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/activesupport/CHANGELOG

    r8854 r8877  
    11*SVN* 
     2 
     3* Serialize BigDecimals as Floats when using to_yaml. #8746 [ernesto.jimenez] 
    24 
    35* Adding TimeWithZone #to_yaml, #to_datetime, #eql? and method aliases for duck-typing compatibility with Time [Geoff Buesing] 
  • trunk/activesupport/lib/active_support/core_ext/bigdecimal/conversions.rb

    r7719 r8877  
     1require 'yaml' 
     2 
    13class BigDecimal #:nodoc: 
    24  alias :_original_to_s :to_s 
     
    46    _original_to_s(format) 
    57  end 
     8 
     9  yaml_as "tag:yaml.org,2002:float" 
     10  def to_yaml( opts = {} ) 
     11    YAML::quick_emit( nil, opts ) do |out| 
     12      # This emits the number without any scientific notation. 
     13      # I prefer it to using self.to_f.to_s, which would lose precision. 
     14      # 
     15      # Note that YAML allows that when reconsituting floats 
     16      # to native types, some precision may get lost. 
     17      # There is no full precision real YAML tag that I am aware of. 
     18      str = self.to_s 
     19      if str == "Infinity" 
     20        str = ".Inf" 
     21      elsif str == "-Infinity" 
     22        str = "-.Inf" 
     23      elsif str == "NaN" 
     24        str = ".NaN" 
     25      end 
     26      out.scalar( "tag:yaml.org,2002:float", str, :plain ) 
     27    end 
     28  end 
    629end