Class: Porridge::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/porridge/serializer.rb

Overview

Serializer is the nominal base class for all porridge serializers.

A serializer is an object that arbitrarily transforms a given input for a given object with a given set of options. The input may be anything, but is typically either a hash or an array. In Rails applications, the object is often an ActiveRecord model. The options may be application-specific.

Serializers are the heart and soul of the porridge gem and are typically layered with composition into a final serializer that is used to actually serialize an object into (typically) a hash or array. Thus, a serializer often simply wraps another serializer, transforming the object or options in some way.

You are encouraged, but not required, to have all your serializers derive from this class. Currently, any object that implements the #call method is a valid serializer.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.ensure_valid!(*objects) ⇒ Boolean

Ensures that all the provided objects are valid serializers, raising InvalidSerializerError if not.

Parameters:

  • objects (Array)

    the splatted array of objects to validate.

Returns:

  • (Boolean)

    true if all the objects were valid; raises an error otherwise.

Raises:



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

def self.ensure_valid!(*objects)
  objects.each { |object| raise InvalidSerializerError unless valid?(object) }
  true
end

.valid?(object) ⇒ Boolean

Determines whether the given object is a valid porridge serializer. Currently, any object that responds to the ‘#call’ method is valid.

Parameters:

  • object

    the object to check.

Returns:

  • (Boolean)

    true if the object is a valid serializer; false otherwise.



21
22
23
# File 'lib/porridge/serializer.rb', line 21

def self.valid?(object)
  object.respond_to? :call
end

Instance Method Details

#call(_object, input, _options) ⇒ Object

Should transforms the given input for the given object with the given options and return the desired output.

Parameters:

  • _object

    the object for which to transform the input.

  • input

    the object being transformed, typically either a hash or an array.

  • _options (Hash)

    a hash of “options,” which may be application specific.

Returns:

  • the transformed output, typically either a hash or an array.



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

def call(_object, input, _options)
  input
end