From bce2c0ce37cbd4abb45ca36362fbb8fae3bbc6b9 Mon Sep 17 00:00:00 2001 From: Jatinder Singh <jatinder.saundh@gmail.com> Date: Fri, 30 Apr 2010 21:02:11 -0700 Subject: Active Model JSON serializer now supports custom root option [#4515 state:committed] Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net> --- activemodel/CHANGELOG | 5 +++++ activemodel/lib/active_model/serializers/json.rb | 6 +++++- .../cases/serializeration/json_serialization_test.rb | 16 ++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/activemodel/CHANGELOG b/activemodel/CHANGELOG index 74aec3bfd3..43cf67d2b7 100644 --- a/activemodel/CHANGELOG +++ b/activemodel/CHANGELOG @@ -1,3 +1,8 @@ +*Rails 3.0.0 [beta 4/release candidate] (unreleased)* + +* JSON supports a custom root option: to_json(:root => 'custom') #4515 [Jatinder Singh] + + *Rails 3.0.0 [beta 3] (April 13th, 2010)* * No changes diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb index 794de7dc55..ffdfbfcaaf 100644 --- a/activemodel/lib/active_model/serializers/json.rb +++ b/activemodel/lib/active_model/serializers/json.rb @@ -79,7 +79,11 @@ module ActiveModel # "title": "So I was thinking"}]} def encode_json(encoder) hash = serializable_hash(encoder.options) - hash = { self.class.model_name.element => hash } if include_root_in_json + if include_root_in_json + custom_root = encoder.options && encoder.options[:root] + hash = { custom_root || self.class.model_name.element => hash } + end + ActiveSupport::JSON.encode(hash) end diff --git a/activemodel/test/cases/serializeration/json_serialization_test.rb b/activemodel/test/cases/serializeration/json_serialization_test.rb index 81df52fcb9..7e89815c96 100644 --- a/activemodel/test/cases/serializeration/json_serialization_test.rb +++ b/activemodel/test/cases/serializeration/json_serialization_test.rb @@ -37,6 +37,22 @@ class JsonSerializationTest < ActiveModel::TestCase end end + test "should include custom root in json" do + begin + Contact.include_root_in_json = true + json = @contact.to_json(:root => 'json_contact') + + assert_match %r{^\{"json_contact":\{}, json + assert_match %r{"name":"Konata Izumi"}, json + assert_match %r{"age":16}, json + assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))})) + assert_match %r{"awesome":true}, json + assert_match %r{"preferences":\{"shows":"anime"\}}, json + ensure + Contact.include_root_in_json = false + end + end + test "should encode all encodable attributes" do json = @contact.to_json -- cgit v1.2.3