Class: Cuprum::Rails::Serializers::Context
- Inherits:
-
Object
- Object
- Cuprum::Rails::Serializers::Context
- 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
-
#serializers ⇒ Hash<Class, Object>
readonly
The configured serializers for different object types.
Instance Method Summary collapse
-
#initialize(serializers:) ⇒ Context
constructor
A new instance of Context.
-
#serialize(object) ⇒ Object
Finds and calls the configured serializer for the given object.
-
#serializer_for(object) ⇒ Object
Finds and initializes the configured serializer for the given object.
Constructor Details
#initialize(serializers:) ⇒ Context
Returns a new instance of Context.
13 14 15 |
# File 'lib/cuprum/rails/serializers/context.rb', line 13 def initialize(serializers:) @serializers = serializers end |
Instance Attribute Details
#serializers ⇒ Hash<Class, Object> (readonly)
Returns 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.
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.
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 |