active_model_serializers/lib/active_model/serializer/collection_serializer.rb
Benjamin Fleischer 3d986377b6 Collapse JSON API success/failure documents in one adapter
Idea per remear (Ben Mills) in the slack:
https://amserializers.slack.com/archives/general/p1455140474000171

remear:

    just so i understand, the adapter in `render json: resource, status: 422, adapter: 'json_api/error',
    serializer: ActiveModel::Serializer::ErrorSerializer` is a different one than, say what i’ve
    specified in a base serializer with `ActiveModel::Serializer.config.adapter = :json_api`. correct?

    and a followup question of, why not same adapter but different serializer?

me:

   With the way the code is written now, it might be possible to not require a special jsonapi adapter.
   However, the behavior is pretty different from the jsonapi adapter.

   this first draft of the PR had it automatically set the adapter if there were errors.  since that
   requires more discussion, I took a step back and made it explicit for this PR

   If I were to re-use the json api adapter and remove the error one, it think the serializable hash
   method would look like

   ```
   def serializable_hash(options = nil)
     return { errors: JsonApi::Error.collection_errors } if serializer.is_a?(ErrorsSerializer)
     return { errors: JsonApi::Error.resource_errors(serializer) } if serializer.is_a?(ErrorSerializer)
     options ||= {}
   ```

   I suppose it could be something more duckish like

   ```
   def serializable_hash(options = nil)
     if serializer.errors? # object.errors.any? || object.any? {|o| o.errors.any? }
       JsonApi::Error.new(serializer).serializable_hash
     else
       # etc
   ```
2016-03-06 12:03:17 -06:00

52 lines
1.3 KiB
Ruby

module ActiveModel
class Serializer
class CollectionSerializer
NoSerializerError = Class.new(StandardError)
include Enumerable
delegate :each, to: :@serializers
attr_reader :object, :root
def initialize(resources, options = {})
@root = options[:root]
@object = resources
@serializers = resources.map do |resource|
serializer_context_class = options.fetch(:serializer_context_class, ActiveModel::Serializer)
serializer_class = options.fetch(:serializer) { serializer_context_class.serializer_for(resource) }
if serializer_class.nil?
fail NoSerializerError, "No serializer found for resource: #{resource.inspect}"
else
serializer_class.new(resource, options.except(:serializer))
end
end
end
def success?
true
end
def json_key
root || derived_root
end
def paginated?
object.respond_to?(:current_page) &&
object.respond_to?(:total_pages) &&
object.respond_to?(:size)
end
protected
attr_reader :serializers
private
def derived_root
key = serializers.first.try(:json_key) || object.try(:name).try(:underscore)
key.try(:pluralize)
end
end
end
end