Completed
Push — dev ( 405831...ff1c91 )
by Fike
57s
created

Factory.create_internal()   A

Complexity

Conditions 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
1
# frozen_string_literal: true
2
3
require_relative '../factory'
4
require_relative '../../mixin/errors'
5
require_relative '../../path/segment'
6
7
module AMA
8
  module Entity
9
    class Mapper
10
      module API
11
        module Default
12
          # Default entity factory
13
          class Factory < API::Factory
14
            include Mixin::Errors
15
16
            INSTANCE = new
17
18
            # @param [AMA::Entity::Mapper::Type] type
19
            # @param [Object] _data
20
            # @param [AMA::Entity::Mapper::Context] context
21
            def create(type, _data, context)
22
              create_internal(type)
23
            rescue StandardError => e
24
              message = "Failed to instantiate #{type} directly from class"
25
              if e.is_a?(ArgumentError)
26
                message += '. Does it have parameterless #initialize() method?'
27
              end
28
              mapping_error(message, parent: e, context: context)
29
            end
30
31
            private
32
33
            def create_internal(type)
34
              entity = type.type.new
35
              type.attributes.values.each do |attribute|
36
                next if attribute.default.nil? || attribute.virtual
37
                segment = Path::Segment.attribute(attribute.name)
38
                value = attribute.default
39
                type.injector.inject(entity, type, attribute, value, segment)
40
              end
41
              entity
42
            end
43
          end
44
        end
45
      end
46
    end
47
  end
48
end
49