Completed
Push — dev ( ffd8f7...ec8098 )
by Fike
51s
created

Entity.initialize()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
1
# frozen-string_literal: true
2
3
require_relative '../../exception/mapping_error'
4
require_relative '../../mixin/errors'
5
6
module AMA
7
  module Entity
8
    class Mapper
9
      class Engine
10
        class Normalizer
11
          # Special normalizer for registered entities
12
          class Entity
13
            include ::AMA::Entity::Mapper::Mixin::Errors
14
15
            def initialize(registry)
16
              @registry = registry
17
            end
18
19
            def normalize(entity, context = nil, target_type = nil)
20
              type = @registry.find!(entity.class)
21
              unless type.normalizer
22
                return normalize_entity(entity, context, target_type)
23
              end
24
              type.normalizer.call(entity, context, target_type) do |handle|
25
                normalize_entity(handle, context, target_type)
26
              end
27
            rescue StandardError => e
28
              message = 'Error while normalizing entity ' \
29
                "of type #{entity.class}"
30
              mapping_error(message, parent: e, context: context)
31
            end
32
33
            def supports(value)
34
              @registry.include?(value.class)
35
            end
36
37
            private
38
39
            def normalize_entity(entity, *)
40
              # TODO: use enumerator
41
              type = @registry.find!(entity.class)
42
              type.attributes.values.each_with_object({}) do |attribute, values|
43
                next values if attribute.sensitive || attribute.virtual
44
                values[attribute.name] = normalize_attribute(entity, attribute)
45
                values
46
              end
47
            end
48
49
            def normalize_attribute(entity, attribute)
50
              # TODO: add attribute normalizer support
51
              entity.instance_variable_get("@#{attribute.name}")
52
            end
53
          end
54
        end
55
      end
56
    end
57
  end
58
end
59