From f26f7b6f843eeb2acdc6e9dbeed7c7b104aa1fc6 Mon Sep 17 00:00:00 2001 From: Jatinder Singh Date: Fri, 30 Apr 2010 01:28:36 -0700 Subject: [PATCH] AR JSON Serializer now supports custom root option. --- .../active_record/serializers/json_serializer.rb | 2 +- activerecord/test/cases/json_serialization_test.rb | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/serializers/json_serializer.rb b/activerecord/lib/active_record/serializers/json_serializer.rb index a20dfbc..5d49381 100644 --- a/activerecord/lib/active_record/serializers/json_serializer.rb +++ b/activerecord/lib/active_record/serializers/json_serializer.rb @@ -79,7 +79,7 @@ module ActiveRecord #:nodoc: def as_json(options = nil) #:nodoc: hash = Serializer.new(self, options).serializable_record - hash = { self.class.model_name.element => hash } if include_root_in_json + hash = { options[:root] || self.class.model_name.element => hash } if include_root_in_json hash end diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb index 54bc8e2..7f13e49 100644 --- a/activerecord/test/cases/json_serialization_test.rb +++ b/activerecord/test/cases/json_serialization_test.rb @@ -43,6 +43,20 @@ class JsonSerializationTest < ActiveRecord::TestCase Contact.include_root_in_json = false end + def test_should_include_root_in_json + 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 + def test_should_encode_all_encodable_attributes json = @contact.to_json -- 1.6.1.3