Permalink
Browse files

AR JSON Serializer now supports custom root option.

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
  • Loading branch information...
1 parent 6dbc75f commit aeff1719ab9c4a0d1a9abd7a609ed8fb9646a0d8 @rubymerchant rubymerchant committed with jeremy Apr 30, 2010
View
@@ -1,5 +1,7 @@
*2.3.6 (pending)*
+* JSON supports a custom root option: to_json(:root => 'custom') #4515 [Jatinder Singh]
+
* Destroy uses optimistic locking. If lock_version on the record you're destroying doesn't match lock_version in the database, a StaleObjectError is raised. #1966 [Curtis Hawthorne]
* To prefix the table names of all models in a module, define self.table_name_prefix on the module. #4032 [Andrew White]
@@ -79,7 +79,7 @@ def to_json(options = {})
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
@@ -43,6 +43,20 @@ def test_should_include_root_in_json
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

0 comments on commit aeff171

Please sign in to comment.