Class: Porridge::ChainSerializer

Inherits:
Serializer show all
Defined in:
lib/porridge/chain_serializer.rb

Overview

ChainSerializer is a serializer that chains multiple other serializers together by passing the output of the first one as the input of the second, and the output of the second as the input of the third, and so on.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Serializer

ensure_valid!, valid?

Constructor Details

#initialize(*serializers) ⇒ ChainSerializer

Creates a new instance of Porridge::ChainSerializer with the given serializers to chain.

Raises:



10
11
12
13
14
# File 'lib/porridge/chain_serializer.rb', line 10

def initialize(*serializers)
  super()
  Serializer.ensure_valid!(*serializers)
  @serializers = serializers
end

Instance Attribute Details

#serializersArray<Serializer, #call> (readonly, private)

The array of chained serializers.



39
40
41
# File 'lib/porridge/chain_serializer.rb', line 39

def serializers
  @serializers
end

Instance Method Details

#call(object, input, options) ⇒ Object

Transforms the given input for the given object with the given options by chaining each serializer (contained in #serializers). The provided input will be given to the first serializer, whose output will be given to the next serializer, and so on for each serializer.

The given object and options will be given to all the provided serializers. Note that the options are not cloned or duplicated. Therefore none of the serializers should mutate the options object or else all the other serializers will also receive the mutated version.



29
30
31
32
33
# File 'lib/porridge/chain_serializer.rb', line 29

def call(object, input, options)
  output = input
  serializers.each { |serializer| output = serializer.call(object, output, options) }
  output
end