Class: ApiSerializer::DataTransformer

Inherits:
Object
  • Object
show all
Defined in:
lib/api_serializer/data_transformer.rb

Overview

The transformer assumes input data uses symbolised keys. Convert before passing if your input uses strings.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target_data_structure) ⇒ DataTransformer

Returns a new instance of DataTransformer.



5
6
7
8
9
10
11
# File 'lib/api_serializer/data_transformer.rb', line 5

def initialize(target_data_structure)
  @target_data_structure = target_data_structure

  if @target_data_structure.attribute_names.empty?
    raise Errors::VariantDefinitionError, "You are trying to create a data transformer (#{@target_data_structure}) but no target attributes are defined, have you forgotten to define some?"
  end
end

Instance Attribute Details

#target_data_structureObject (readonly)

Returns the value of attribute target_data_structure.



13
14
15
# File 'lib/api_serializer/data_transformer.rb', line 13

def target_data_structure
  @target_data_structure
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



27
28
29
# File 'lib/api_serializer/data_transformer.rb', line 27

def ==(other)
  target_data_structure == other.target_data_structure
end

#inspectObject



23
24
25
# File 'lib/api_serializer/data_transformer.rb', line 23

def inspect
  "#<#{self.class.name} (#{@target_data_structure.inspect})>"
end

#transform(data, context = {}) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/api_serializer/data_transformer.rb', line 15

def transform(data, context = {})
  mapped_data = perform_transform_and_mapping(data, context)
  @target_data_structure.new(**mapped_data)
rescue Literal::TypeError, ArgumentError => e
  message = "The data transform failed as the data does not abide to the schema. \"#{e.message}\" - on (#{@target_data_structure.name})"
  raise Errors::DataTransformError, message
end