diff options
author | Godfrey Chan <godfreykfc@gmail.com> | 2013-11-12 01:57:21 -0800 |
---|---|---|
committer | Godfrey Chan <godfreykfc@gmail.com> | 2013-11-14 15:46:43 -0800 |
commit | 0f33d70e89991711ff8b3dde134a61f4a5a0ec06 (patch) | |
tree | df93bc8ab410476175fd07f61105ff09ad86084a /activesupport/test/json | |
parent | 07996ebc50f5906dbecc481ac83ed2adefc9ec6e (diff) | |
download | rails-0f33d70e89991711ff8b3dde134a61f4a5a0ec06.tar.gz rails-0f33d70e89991711ff8b3dde134a61f4a5a0ec06.tar.bz2 rails-0f33d70e89991711ff8b3dde134a61f4a5a0ec06.zip |
Improved compatibility with the stdlib JSON gem.
Previously, calling `::JSON.{generate,dump}` sometimes causes
unexpected failures such as intridea/multi_json#86.
`::JSON.{generate,dump}` now bypasses the ActiveSupport JSON encoder
completely and yields the same result with or without ActiveSupport.
This means that it will **not** call `as_json` and will ignore any
options that the JSON gem does not natively understand. To invoke
ActiveSupport's JSON encoder instead, use `obj.to_json(options)` or
`ActiveSupport::JSON.encode(obj, options)`.
Diffstat (limited to 'activesupport/test/json')
-rw-r--r-- | activesupport/test/json/encoding_test.rb | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index 856ca75cbc..39da760bf2 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -32,6 +32,19 @@ class TestJSONEncoding < ActiveSupport::TestCase end end + class HashWithAsJson < Hash + attr_accessor :as_json_called + + def initialize(*) + super + end + + def as_json(options={}) + @as_json_called = true + super + end + end + TrueTests = [[ true, %(true) ]] FalseTests = [[ false, %(false) ]] NilTests = [[ nil, %(null) ]] @@ -367,6 +380,38 @@ class TestJSONEncoding < ActiveSupport::TestCase assert_equal false, false.as_json end + def test_json_gem_dump_by_passing_active_support_encoder + h = HashWithAsJson.new + h[:foo] = "hello" + h[:bar] = "world" + + assert_equal %({"foo":"hello","bar":"world"}), JSON.dump(h) + assert_nil h.as_json_called + end + + def test_json_gem_generate_by_passing_active_support_encoder + h = HashWithAsJson.new + h[:foo] = "hello" + h[:bar] = "world" + + assert_equal %({"foo":"hello","bar":"world"}), JSON.generate(h) + assert_nil h.as_json_called + end + + def test_json_gem_pretty_generate_by_passing_active_support_encoder + h = HashWithAsJson.new + h[:foo] = "hello" + h[:bar] = "world" + + assert_equal <<EXPECTED.chomp, JSON.pretty_generate(h) +{ + "foo": "hello", + "bar": "world" +} +EXPECTED + assert_nil h.as_json_called + end + protected def object_keys(json_object) |