Skip to content

Commit

Permalink
Merge 38cb096 into 3201c63
Browse files Browse the repository at this point in the history
  • Loading branch information
vad4msiu committed Mar 11, 2014
2 parents 3201c63 + 38cb096 commit a71e4ed
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/active_model/serializable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,15 @@ module Serializable
def as_json(options={})
if root = options.fetch(:root, json_key)
hash = { root => serializable_object }
hash.merge!(serializable_data)

serializable_data.each_pair do |key, value|
if hash[key].is_a?(Array)
hash[key].concat(value)
else
hash[key] = value
end
end

hash
else
serializable_object
Expand All @@ -22,4 +30,4 @@ def embedded_in_root_associations
{}
end
end
end
end
14 changes: 14 additions & 0 deletions test/fixtures/poro.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ def comments
class Comment < Model
end

class Catalog < Model
def sub_catalogs
@attributes[:sub_catalogs] ||= [
Catalog.new(name: 'Catalog 1', :sub_catalogs => []),
Catalog.new(name: 'Catalog 2', :sub_catalogs => [])
]
end
end

###
## Serializers
###
Expand Down Expand Up @@ -62,3 +71,8 @@ class PostSerializer < ActiveModel::Serializer
class CommentSerializer < ActiveModel::Serializer
attributes :content
end

class CatalogSerializer < ActiveModel::Serializer
attributes :name
has_many :sub_catalogs, root: :catalogs, embed: :ids, embed_in_root: true #serializer: CatalogSerializer
end
17 changes: 17 additions & 0 deletions test/unit/active_model/array_serializer/root_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,5 +98,22 @@ def test_root_as_argument_takes_precedence
}, @rooted_serializer.as_json(root: :argument))
end
end

class DuplicateRootKeysTest < Minitest::Test
def setup
@catalog = Catalog.new({ name: 'Catalog root' })
@serializer = ArraySerializer.new([@catalog], root: :catalogs)
end

def test_duplicate_root_keys_using_as_json
assert_equal({
catalogs: [
{ name: 'Catalog root', 'sub_catalog_ids' => @catalog.sub_catalogs.map(&:object_id) },
{ name: 'Catalog 1', 'sub_catalog_ids' => [] },
{ name: 'Catalog 2', 'sub_catalog_ids' => [] },
]
}, @serializer.as_json)
end
end
end
end

0 comments on commit a71e4ed

Please sign in to comment.