Completed
Push — dev ( ff1c91...ab1075 )
by Fike
01:06
created

SetType.initialize()   A

Complexity

Conditions 1

Size

Total Lines 10

Duplication

Lines 10
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 10
loc 10
rs 9.4285
cc 1
1
# frozen_string_literal: true
2
3
require 'set'
4
5
require_relative '../../type'
6
require_relative '../../path/segment'
7
require_relative '../../mixin/errors'
8
9
module AMA
10
  module Entity
11
    class Mapper
12 View Code Duplication
      class Type
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
13
        module BuiltIn
14
          # Predefined type for Set class
15
          class SetType < Type
16
            def initialize
17
              super(::Set)
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
                Set.new([])
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 Set from #{data.class}"
45
                  type.mapping_error(message, context: context)
46
                end
47
                Set.new(data)
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, *|
64
                entity.add(value)
65
              end
66
            end
67
68
            INSTANCE = new
69
          end
70
        end
71
      end
72
    end
73
  end
74
end
75