Class: Cuprum::Rails::Serializers::Context

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

Overview

Encapsulates and applies configuration for performing serialization.

Defined Under Namespace

Classes: UndefinedSerializerError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(serializers:) ⇒ Context

Returns a new instance of Context.

Parameters:

  • serializers (Hash<Class, Object>)

    The configured serializers for different object types.



13
14
15
# File 'lib/cuprum/rails/serializers/context.rb', line 13

def initialize(serializers:)
  @serializers = serializers
end

Instance Attribute Details

#serializersHash<Class, Object> (readonly)

Returns The configured serializers for different object types.

Returns:

  • (Hash<Class, Object>)

    The configured serializers for different object types.



19
20
21
# File 'lib/cuprum/rails/serializers/context.rb', line 19

def serializers
  @serializers
end

Instance Method Details

#serialize(object) ⇒ Object

Finds and calls the configured serializer for the given object.

Parameters:

  • object (Object)

    The object to serialize.

Returns:

  • (Object)

    the serialized representation of the object.

Raises:

See Also:



31
32
33
# File 'lib/cuprum/rails/serializers/context.rb', line 31

def serialize(object)
  serializer_for(object).call(object, context: self)
end

#serializer_for(object) ⇒ Object

Finds and initializes the configured serializer for the given object.

If the configured serializer is a Class and responds to the .instance class method, then #serializer_for will return the value of .instance. If the configured serializer is a Class but does not respond to .instance, a new instance of the serializer class will be created using .new and returned. If the configured serializer is not a Class, #serializer_for will return the configured serializer.

The return value is cached across multiple calls to #serializer_for.

Parameters:

  • object (Object)

    The object to serialize.

Returns:

  • (Object)

    the serializer instance for that object.

Raises:



52
53
54
# File 'lib/cuprum/rails/serializers/context.rb', line 52

def serializer_for(object)
  (@cached_serializers ||= {})[object.class] ||= find_serializer_for(object)
end