KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Using Ruby on Rails I have a couple of fields that are serialized (arrays or hashes mostly). Some of those contain BigDecimal s. It is very important that those big decimals remain big decimals, but Rails is turning them into floats. How do I get BigDecimal s back? Looking into this issue I found that serializing a big decimal in plain Ruby, without Rails, works as expected: BigDecimal.new("42.42").to_yaml => "--- !ruby/object:BigDecimal 18:0.4242E2\n...\n" but in a Rails console it doesn't: BigDecimal.new("42.42").to_yaml => "--- 42.42\n" That number is the string representation of the big decimal, so it's all-right. But when I read it back it is read as a float, so even if I convert it to BigDecimal (something I don't want to do as it's error prone), it is possible I'll lose precision, which isn't acceptable for my app. I tracked down the culprit to activesupport-3.2.11/lib/active_support/core_ext/big_decimal/conversions.rb which overrides the following method in BigDecimal: YAML_TAG = 'tag:yaml.org,2002:float' YAML_MAPPING = { 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' } # This emits the number without any scientific notation. # This is better than self.to_f.to_s since it doesn't lose precision. # # Note that reconstituting YAML floats to native floats may lose precision. def to_yaml(opts = {}) return super if defined?(YAML::ENGINE) && !YAML::ENGINE.syck? YAML.quick_emit(nil, opts) do |out| string = to_s out.scalar(YAML_TAG, YAML_MAPPING[string] || string, :plain) end end Why would they do that? And more importantly, how do I work-around it?
Tags (comma-separated)
Save Edits
Cancel