Allow to set embed options from AM::Serializer

This commit is contained in:
Santiago Pastorino 2013-09-15 20:29:43 -03:00
parent aa23e811cc
commit 10e882a14f
3 changed files with 12 additions and 3 deletions

View File

@ -17,6 +17,11 @@ module ActiveModel
yield SETTINGS yield SETTINGS
end end
def embed(type, options={})
SETTINGS[:embed] = type
SETTINGS[:include] = true if options[:include]
end
def serializer_for(resource) def serializer_for(resource)
if resource.respond_to?(:to_ary) if resource.respond_to?(:to_ary)
ArraySerializer ArraySerializer

View File

@ -8,8 +8,8 @@ module ActiveModel
@name = name @name = name
@options = options @options = options
self.embed = options[:embed] self.embed = options[:embed] || SETTINGS[:embed]
@embed_in_root = @embed_ids && options[:include] @embed_in_root = @embed_ids && (options[:include] || SETTINGS[:include])
@embed_key = options[:embed_key] || :id @embed_key = options[:embed_key] || :id
@key = options[:key] @key = options[:key]
@embedded_key = options[:root] @embedded_key = options[:root]

View File

@ -84,12 +84,16 @@ module ActiveModel
end end
def test_associations_embedding_ids_including_objects_serialization_using_as_json def test_associations_embedding_ids_including_objects_serialization_using_as_json
@association.embed_in_root = true PostSerializer.embed :ids, include: true
PostSerializer._associations[0].send :initialize, @association.name, @association.options
@post_serializer.root = nil @post_serializer.root = nil
assert_equal({ assert_equal({
'post' => { 'title' => 'Title 1', 'body' => 'Body 1', 'comment_ids' => @post.comments.map { |c| c.object_id } }, 'post' => { 'title' => 'Title 1', 'body' => 'Body 1', 'comment_ids' => @post.comments.map { |c| c.object_id } },
'comments' => [{ 'content' => 'C1' }, { 'content' => 'C2' }] 'comments' => [{ 'content' => 'C1' }, { 'content' => 'C2' }]
}, @post_serializer.as_json) }, @post_serializer.as_json)
ensure
SETTINGS.clear
end end
def test_associations_using_a_given_serializer def test_associations_using_a_given_serializer