Class: Porridge::ArraySerializer
- Inherits:
-
Serializer
- Object
- Serializer
- Porridge::ArraySerializer
- Defined in:
- lib/porridge/array_serializer.rb
Overview
ArraySerializer is a serializer that wraps another serializer, calling it for every element of the input array, if an array was given, or simply passing it the input if not.
Instance Attribute Summary collapse
-
#base ⇒ Serializer, #call
readonly
private
The base serializer, which will be called for the object, or each object, if an array is given.
Instance Method Summary collapse
-
#array?(object) ⇒ Boolean
protected
Determines whether the given object is an array for the purposes of this ArraySerializer instance.
-
#call(object_or_objects, input, options) ⇒ Object+
Serializes the given object, which may be an array, for the given input with the given options.
-
#initialize(base) ⇒ ArraySerializer
constructor
Creates a new instance of ArraySerializer with the given base serializer.
Methods inherited from Serializer
Constructor Details
#initialize(base) ⇒ ArraySerializer
Creates a new instance of Porridge::ArraySerializer with the given base serializer.
11 12 13 14 15 |
# File 'lib/porridge/array_serializer.rb', line 11 def initialize(base) Serializer.ensure_valid!(base) @base = base super() end |
Instance Attribute Details
#base ⇒ Serializer, #call (readonly, private)
The base serializer, which will be called for the object, or each object, if an array is given.
53 54 55 |
# File 'lib/porridge/array_serializer.rb', line 53 def base @base end |
Instance Method Details
#array?(object) ⇒ Boolean (protected)
Determines whether the given object is an array for the purposes of this Porridge::ArraySerializer instance. The default implementation simple checks to see if the object implements the map
method. You may override this method to change the default behavior, if, for example, you have a non-array that implements map
.
45 46 47 |
# File 'lib/porridge/array_serializer.rb', line 45 def array?(object) object.is_a? Array end |
#call(object_or_objects, input, options) ⇒ Object+
Serializes the given object, which may be an array, for the given input with the given options. If the object is an array (according to #array?), the base serializer #base will be called for each element, and an array with each result will be returned. If the object is not an array, will simply delegate to #base.
The given object and options will be given to the base serializer for every element. Note that the options are not cloned or duplicated. Therefore the base serializer must not mutate the options object or else the other invocations will also receive the mutated version.
30 31 32 33 34 35 36 |
# File 'lib/porridge/array_serializer.rb', line 30 def call(object_or_objects, input, ) if array?(object_or_objects) object_or_objects.map { |object| base.call(object, input, ) } else base.call(object_or_objects, input, ) end end |