Class: Trane::Serializer

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

Instance Method Summary collapse

Constructor Details

#initialize(response_definition, registry, strict_mode: :ignore) ⇒ Serializer

Instances are frozen post-init; share freely across threads.

Parameters:

  • response_definition (ResponseDefinition)
  • registry (Module)

    Trane::Registry

  • strict_mode (Symbol) (defaults to: :ignore)

    :raise, :log, or :ignore



9
10
11
12
13
14
# File 'lib/trane/serializer.rb', line 9

def initialize(response_definition, registry, strict_mode: :ignore)
  @response_definition = response_definition
  @registry            = registry
  @strict_mode         = strict_mode
  freeze
end

Instance Method Details

#serialize(data, extra_attributes: ExtraAttributesFilter::EMPTY) ⇒ Hash

Serialize data according to the response definition.

Parameters:

  • data (Hash, Object)

    the data to serialize (hash of root-level keys)

  • extra_attributes (Set<String>) (defaults to: ExtraAttributesFilter::EMPTY)

    dot-notation paths of extra fields to include

Returns:

  • (Hash)

    serialized result



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/trane/serializer.rb', line 21

def serialize(data, extra_attributes: ExtraAttributesFilter::EMPTY)
  result = serialize_fields(@response_definition.fields, data, extra_attributes: extra_attributes, prefix: "")

  if @strict_mode != :ignore
    ContractValidator.validate_response!(
      @response_definition, result, @registry, mode: @strict_mode
    )
  end

  result
end