mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
BigDecimal string wrapping in JSON serialization can now be opted-out, fixes #6033
This commit is contained in:
parent
c0a7038412
commit
18aa1ae29c
3 changed files with 28 additions and 1 deletions
|
@ -32,6 +32,9 @@
|
|||
|
||||
* Unicode database updated to 6.1.0.
|
||||
|
||||
* Adds `encode_big_decimal_as_string` option to force JSON serialization of BigDecimals as numeric instead
|
||||
of wrapping them in strings for safety.
|
||||
|
||||
|
||||
## Rails 3.2.2 (March 1, 2012) ##
|
||||
|
||||
|
|
|
@ -17,6 +17,7 @@ module ActiveSupport
|
|||
class << self
|
||||
delegate :use_standard_json_time_format, :use_standard_json_time_format=,
|
||||
:escape_html_entities_in_json, :escape_html_entities_in_json=,
|
||||
:encode_big_decimal_as_string, :encode_big_decimal_as_string=,
|
||||
:to => :'ActiveSupport::JSON::Encoding'
|
||||
end
|
||||
|
||||
|
@ -104,6 +105,9 @@ module ActiveSupport
|
|||
# If true, use ISO 8601 format for dates and times. Otherwise, fall back to the Active Support legacy format.
|
||||
attr_accessor :use_standard_json_time_format
|
||||
|
||||
# If false, serializes BigDecimal objects as numeric instead of wrapping them in a string
|
||||
attr_accessor :encode_big_decimal_as_string
|
||||
|
||||
attr_accessor :escape_regex
|
||||
attr_reader :escape_html_entities_in_json
|
||||
|
||||
|
@ -133,6 +137,7 @@ module ActiveSupport
|
|||
|
||||
self.use_standard_json_time_format = true
|
||||
self.escape_html_entities_in_json = false
|
||||
self.encode_big_decimal_as_string = true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -197,7 +202,15 @@ class BigDecimal
|
|||
# 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.
|
||||
def as_json(options = nil) finite? ? to_s : NilClass::AS_JSON end #:nodoc:
|
||||
#
|
||||
# Use ActiveSupport.use_standard_json_big_decimal_format = true to override this behaviour
|
||||
def as_json(options = nil) #:nodoc:
|
||||
if finite?
|
||||
ActiveSupport.encode_big_decimal_as_string ? to_s : self
|
||||
else
|
||||
NilClass::AS_JSON
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
class Regexp
|
||||
|
|
|
@ -274,6 +274,17 @@ class TestJSONEncoding < ActiveSupport::TestCase
|
|||
JSON.parse(json_string_and_date))
|
||||
end
|
||||
|
||||
def test_opt_out_big_decimal_string_serialization
|
||||
big_decimal = BigDecimal('2.5')
|
||||
|
||||
begin
|
||||
ActiveSupport.encode_big_decimal_as_string = false
|
||||
assert_equal big_decimal.to_s, big_decimal.to_json
|
||||
ensure
|
||||
ActiveSupport.encode_big_decimal_as_string = true
|
||||
end
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
def object_keys(json_object)
|
||||
|
|
Loading…
Reference in a new issue