Class: Cuprum::Rails::Serializers::BaseSerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/cuprum/rails/serializers/base_serializer.rb

Overview

Converts objects or data structures based on configured serializers.

Defined Under Namespace

Classes: RecursiveSerializerError, UndefinedSerializerError

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.instanceCuprum::Rails::Serializers::Serializer

Returns a cached instance of the serializer.

Returns:

  • (Cuprum::Rails::Serializers::Serializer)

    a cached instance of the serializer.



16
17
18
# File 'lib/cuprum/rails/serializers/base_serializer.rb', line 16

def self.instance
  @instance ||= new
end

Instance Method Details

#call(object, context:) ⇒ Object

Converts the object to a serialized representation.

First, #call finds the best serializer from the :serializers Hash. This is done by walking up the object class’s ancestors to find the closest ancestor which is a key in the :serializers Hash. The corresponding value is then called with the object.

Parameters:

  • object (Object)

    The object to serialize.

  • context (Cuprum::Rails::Serializers::Context)

    The serialization context, which includes the configured serializers for attributes or collection items.

Returns:

  • (Object)

    a serialized representation of the object.

Raises:

  • RecursiveSerializerError if the serializer would create an infinite loop, e.g. by calling itself.

  • UndefinedSerializerError if there is no matching serializer for the object.



38
39
40
41
42
# File 'lib/cuprum/rails/serializers/base_serializer.rb', line 38

def call(object, context:)
  handle_recursion!(object, context: context)

  context.serialize(object)
end