Sha256: 3535423d5a6c01b1a5a6b09e66f6f378ca4ad1e4fcb233c3cb76f88a96e5619f

Contents?: true

Size: 1.33 KB

Versions: 14

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true

module Panko
  class ArraySerializer
    attr_accessor :subjects

    def initialize(subjects, options = {})
      @subjects = subjects
      @each_serializer = options[:each_serializer]

      if @each_serializer.nil?
        raise ArgumentError, %{
Please pass valid each_serializer to ArraySerializer, for example:
> Panko::ArraySerializer.new(posts, each_serializer: PostSerializer)
        }
      end

      serializer_options = {
        only: options.fetch(:only, []),
        except: options.fetch(:except, []),
        context: options[:context],
        scope: options[:scope]
      }

      @serialization_context = SerializationContext.create(options)
      @descriptor = Panko::SerializationDescriptor.build(@each_serializer, serializer_options, @serialization_context)
    end

    def to_json
      serialize_to_json @subjects
    end

    def serialize(subjects)
      serialize_with_writer(subjects, Panko::ObjectWriter.new).output
    end

    def to_a
      serialize_with_writer(@subjects, Panko::ObjectWriter.new).output
    end

    def serialize_to_json(subjects)
      serialize_with_writer(subjects, Oj::StringWriter.new(mode: :rails)).to_s
    end

    private

    def serialize_with_writer(subjects, writer)
      Panko.serialize_objects(subjects.to_a, writer, @descriptor)
      writer
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
panko_serializer-0.8.3 lib/panko/array_serializer.rb
panko_serializer-0.8.2 lib/panko/array_serializer.rb
panko_serializer-0.8.1 lib/panko/array_serializer.rb
panko_serializer-0.8.0 lib/panko/array_serializer.rb
panko_serializer-0.7.9 lib/panko/array_serializer.rb
panko_serializer-0.7.7 lib/panko/array_serializer.rb
panko_serializer-0.7.6 lib/panko/array_serializer.rb
panko_serializer-0.7.5 lib/panko/array_serializer.rb
panko_serializer-0.7.4 lib/panko/array_serializer.rb
panko_serializer-0.7.3 lib/panko/array_serializer.rb
panko_serializer-0.7.2 lib/panko/array_serializer.rb
panko_serializer-0.7.1 lib/panko/array_serializer.rb
panko_serializer-0.7.0 lib/panko/array_serializer.rb
panko_serializer-0.6.0 lib/panko/array_serializer.rb