Skip to content

Commit

Permalink
fixed a bug with the json serialization when the class setting is set…
Browse files Browse the repository at this point in the history
… to not include the root, but an instance is serialized with the root option passed as true
  • Loading branch information
mattetti committed Sep 22, 2011
1 parent 8aa537c commit 6e78bbe
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
22 changes: 10 additions & 12 deletions activemodel/lib/active_model/serializers/json.rb
Expand Up @@ -88,19 +88,17 @@ module JSON
# "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)
Expand Down
10 changes: 10 additions & 0 deletions activemodel/test/cases/serializers/json_serialization_test.rb
Expand Up @@ -56,6 +56,16 @@ def setup
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)
Expand Down

0 comments on commit 6e78bbe

Please sign in to comment.