Class: BigDecimal
- Defined in:
- activesupport/lib/active_support/core_ext/object/json.rb,
activesupport/lib/active_support/core_ext/object/duplicable.rb,
activesupport/lib/active_support/core_ext/big_decimal/conversions.rb,
activesupport/lib/active_support/core_ext/big_decimal/yaml_conversions.rb
Constant Summary collapse
- DEFAULT_STRING_FORMAT =
'F'
- YAML_MAPPING =
{ 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' }
Instance Method Summary collapse
-
#as_json(options = nil) ⇒ Object
A BigDecimal would be naturally represented as a JSON number.
- #encode_with(coder) ⇒ Object
- #to_formatted_s(*args) ⇒ Object (also: #to_s)
Instance Method Details
#as_json(options = nil) ⇒ Object
A BigDecimal would be naturally represented as a JSON number. Most libraries, however, parse non-integer JSON numbers directly as floats. Clients using those libraries would get in general a wrong number and no way to recover other than manually inspecting the string with the JSON code itself.
That’s why a JSON string is returned. The JSON literal is not numeric, but if the other end knows by contract that the data is supposed to be a BigDecimal, it still has the chance to post-process the string and get the real value.
115 116 117 |
# File 'activesupport/lib/active_support/core_ext/object/json.rb', line 115 def as_json( = nil) #:nodoc: finite? ? to_s : nil end |
#encode_with(coder) ⇒ Object
10 11 12 13 |
# File 'activesupport/lib/active_support/core_ext/big_decimal/yaml_conversions.rb', line 10 def encode_with(coder) string = to_s coder.represent_scalar(nil, YAML_MAPPING[string] || string) end |
#to_formatted_s(*args) ⇒ Object Also known as: to_s
6 7 8 9 10 11 12 13 |
# File 'activesupport/lib/active_support/core_ext/big_decimal/conversions.rb', line 6 def to_formatted_s(*args) if args[0].is_a?(Symbol) super else format = args[0] || DEFAULT_STRING_FORMAT _original_to_s(format) end end |