Move Serializer#serialize into Serializer#serializable_hash

This commit is contained in:
Benjamin Fleischer
2016-06-05 23:01:21 -05:00
parent caf4910b6e
commit 7254d34c90
3 changed files with 41 additions and 38 deletions

View File

@@ -11,22 +11,23 @@ module ActiveModel
@object = resources
@options = options
@root = options[:root]
serializer_context_class = options.fetch(:serializer_context_class, ActiveModel::Serializer)
@serializers = resources.map do |resource|
serializer_class = options.fetch(:serializer) { serializer_context_class.serializer_for(resource) }
if serializer_class.nil? # rubocop:disable Style/GuardClause
fail NoSerializerError, "No serializer found for resource: #{resource.inspect}"
else
serializer_class.new(resource, options.except(:serializer))
end
end
@serializers = serializers_from_resources
end
def success?
true
end
# @api private
def serializable_hash(adapter_options, options, adapter_instance)
include_directive = ActiveModel::Serializer.include_directive_from_options(adapter_options)
adapter_options[:cached_attributes] ||= ActiveModel::Serializer.cache_read_multi(self, adapter_instance, include_directive)
adapter_opts = adapter_options.merge(include_directive: include_directive)
serializers.map do |serializer|
serializer.serializable_hash(adapter_opts, options, adapter_instance)
end
end
# TODO: unify naming of root, json_key, and _type. Right now, a serializer's
# json_key comes from the root option or the object's model name, by default.
# But, if a dev defines a custom `json_key` method with an explicit value,
@@ -56,19 +57,28 @@ module ActiveModel
object.respond_to?(:size)
end
# @api private
def serialize(adapter_options, options, adapter_instance)
include_directive = ActiveModel::Serializer.include_directive_from_options(adapter_options)
adapter_options[:cached_attributes] ||= ActiveModel::Serializer.cache_read_multi(self, adapter_instance, include_directive)
adapter_opts = adapter_options.merge(include_directive: include_directive)
serializers.map do |serializer|
serializer.serialize(adapter_opts, options, adapter_instance)
end
end
protected
attr_reader :serializers, :options
private
def serializers_from_resources
serializer_context_class = options.fetch(:serializer_context_class, ActiveModel::Serializer)
object.map do |resource|
serializer_from_resource(resource, serializer_context_class, options)
end
end
def serializer_from_resource(resource, serializer_context_class, options)
serializer_class = options.fetch(:serializer) { serializer_context_class.serializer_for(resource) }
if serializer_class.nil? # rubocop:disable Style/GuardClause
fail NoSerializerError, "No serializer found for resource: #{resource.inspect}"
else
serializer_class.new(resource, options.except(:serializer))
end
end
end
end
end