aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJosé Valim <jose.valim@gmail.com>2011-09-22 14:24:39 -0700
committerJosé Valim <jose.valim@gmail.com>2011-09-22 14:24:39 -0700
commitc19c55582bf46541d0ae095ea70b65cf18aff775 (patch)
treec7914648baa0417a45013cb5e253c6dc5756909d
parent9d46823b5d00e78c6ffaaae731a9a7acf6bb2b14 (diff)
parent6e78bbea90f744fb7de3bc93752d1519503a370d (diff)
downloadrails-c19c55582bf46541d0ae095ea70b65cf18aff775.tar.gz
rails-c19c55582bf46541d0ae095ea70b65cf18aff775.tar.bz2
rails-c19c55582bf46541d0ae095ea70b65cf18aff775.zip
Merge pull request #3106 from mattetti/master
ActiveModel JSON serialization bug fix
-rw-r--r--activemodel/lib/active_model/serializers/json.rb22
-rw-r--r--activemodel/test/cases/serializers/json_serialization_test.rb10
2 files changed, 20 insertions, 12 deletions
diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb
index 4fbccd7419..3c713311fd 100644
--- a/activemodel/lib/active_model/serializers/json.rb
+++ b/activemodel/lib/active_model/serializers/json.rb
@@ -88,19 +88,17 @@ module ActiveModel
# "title": "So I was thinking"}]}
def as_json(options = nil)
- hash = serializable_hash(options)
-
- include_root = include_root_in_json
- if options.try(:key?, :root)
- include_root = options[:root]
- end
-
- if include_root
- custom_root = options && options[:root]
- hash = { custom_root || self.class.model_name.element => hash }
+ opts_root = options[:root] if options.try(:key?, :root)
+ if opts_root
+ custom_root = opts_root == true ? self.class.model_name.element : opts_root
+ { custom_root => serializable_hash(options) }
+ elsif opts_root == false
+ serializable_hash(options)
+ elsif include_root_in_json
+ { self.class.model_name.element => serializable_hash(options) }
+ else
+ serializable_hash(options)
end
-
- hash
end
def from_json(json, include_root=include_root_in_json)
diff --git a/activemodel/test/cases/serializers/json_serialization_test.rb b/activemodel/test/cases/serializers/json_serialization_test.rb
index 5e1e7d897a..40fdcf20ca 100644
--- a/activemodel/test/cases/serializers/json_serialization_test.rb
+++ b/activemodel/test/cases/serializers/json_serialization_test.rb
@@ -56,6 +56,16 @@ class JsonSerializationTest < ActiveModel::TestCase
end
end
+ test "should include root in json (option) even if the default is set to false" do
+ begin
+ Contact.include_root_in_json = false
+ json = @contact.to_json(:root => true)
+ assert_match %r{^\{"contact":\{}, json
+ ensure
+ Contact.include_root_in_json = true
+ end
+ end
+
test "should not include root in json (option)" do
json = @contact.to_json(:root => false)