Sha256: 8f630001b4ed01c0aae1f38876304695523f3b6c7aefd058e4de8d34a22bae51

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

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 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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_model_serializers-0.10.0.rc4 lib/active_model/serializer/collection_serializer.rb