EnumerableType   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
dl 0
loc 57
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A define_factory() 0 5 1
A define_normalizer() 0 5 1
A define_injector() 0 5 1
A define_enumerator() 0 10 1
A initialize() 0 10 1
A define_denormalizer() 0 9 1
1
# frozen_string_literal: true
2
3
require_relative '../../type'
4
require_relative '../../path/segment'
5
require_relative '../../mixin/errors'
6
7
module AMA
8
  module Entity
9
    class Mapper
10
      class Type
11
        module BuiltIn
12
          # Default Enumerable handler
13
          class EnumerableType < Type
14
            include Mixin::Errors
15
16
            def initialize
17
              super(::Enumerable)
18
              attribute!(:_value, parameter!(:T), virtual: true)
19
20
              define_factory
21
              define_normalizer
22
              define_denormalizer
23
              define_enumerator
24
              define_injector
25
            end
26
27
            private
28
29
            def define_factory
30
              factory_block do |*|
31
                []
32
              end
33
            end
34
35
            def define_normalizer
36
              normalizer_block do |input, *|
37
                input.map(&:itself)
38
              end
39
            end
40
41
            def define_denormalizer
42
              denormalizer_block do |data, type, context = nil, *|
43
                if data.is_a?(Hash) || !data.is_a?(Enumerable)
44
                  message = "Can't denormalize Enumerable from #{data.class}"
45
                  type.mapping_error(message, context: context)
46
                end
47
                data.map(&:itself)
48
              end
49
            end
50
51
            def define_enumerator
52
              enumerator_block do |entity, type, *|
53
                ::Enumerator.new do |yielder|
54
                  attribute = type.attributes[:_value]
55
                  entity.each_with_index do |value, index|
56
                    yielder << [attribute, value, Path::Segment.index(index)]
57
                  end
58
                end
59
              end
60
            end
61
62
            def define_injector
63
              injector_block do |entity, _, _, value, context|
64
                entity[context.path.current.name] = value
65
              end
66
            end
67
68
            INSTANCE = new
69
          end
70
        end
71
      end
72
    end
73
  end
74
end
75