Clean up HasOne array wrapping logic

Introduce private _wrap_in_array option for now.
This commit is contained in:
Adrian Mugnolo and Santiago Pastorino 2013-12-17 15:39:15 -02:00 committed by Santiago Pastorino
parent 28fbb62ec4
commit f14f931957
3 changed files with 11 additions and 24 deletions

View File

@ -133,8 +133,7 @@ end
if association.embed_ids?
hash[association.key] = serialize_ids association
elsif association.embed_objects?
associated_data = send(association.name)
hash[association.embedded_key] = serialize(association, associated_data)
hash[association.embedded_key] = serialize association
end
end
end
@ -150,14 +149,14 @@ end
associations.each_with_object({}) do |(name, association), hash|
if included_associations.include? name
if association.embed_in_root?
associated_data = Array(send(association.name))
hash[association.root_key] = serialize(association, associated_data)
hash[association.root_key] = serialize association
end
end
end
end
def serialize(association, object)
def serialize(association)
object = send(association.name)
association.build_serializer(object, scope: scope).serializable_object
end
@ -174,6 +173,7 @@ end
return nil if object.nil?
hash = attributes
hash.merge! associations
@options[:_wrap_in_array] ? [hash] : hash
end
alias_method :serializable_object, :serializable_hash
end

View File

@ -38,13 +38,6 @@ module ActiveModel
@serializer_class.new(object, options.merge(@options))
end
private
def use_array_serializer!
@options.merge!(each_serializer: @serializer_class)
@serializer_class = ArraySerializer
end
class HasOne < Association
def initialize(name, *args)
super
@ -53,12 +46,8 @@ module ActiveModel
end
def build_serializer(object, options = {})
if object.respond_to?(:to_ary) && !(@serializer_class && @serializer_class <= ArraySerializer)
use_array_serializer!
else
@serializer_class ||= Serializer.serializer_for(object) || DefaultSerializer
end
@serializer_class ||= Serializer.serializer_for(object) || DefaultSerializer
options[:_wrap_in_array] = embed_in_root?
super
end
end
@ -72,7 +61,8 @@ module ActiveModel
def build_serializer(object, options = {})
if @serializer_class && !(@serializer_class <= ArraySerializer)
use_array_serializer!
@options[:each_serializer] = @serializer_class
@serializer_class = ArraySerializer
else
@serializer_class ||= ArraySerializer
end

View File

@ -11,11 +11,8 @@ module ActiveModel
def test_build_serializer_for_array_called_twice
2.times do
serializer = @association.build_serializer([@post])
each_serializer = serializer.serializer_for(@post)
assert_instance_of(ArraySerializer, serializer)
assert_instance_of(PostSerializer, each_serializer)
serializer = @association.build_serializer(@post)
assert_instance_of(PostSerializer, serializer)
end
end
end