|
1
|
|
|
# frozen_string_literal: true |
|
2
|
|
|
|
|
3
|
|
|
require_relative '../../exception/mapping_error' |
|
4
|
|
|
require_relative '../../mixin/reflection' |
|
5
|
|
|
require_relative '../../mixin/errors' |
|
6
|
|
|
|
|
7
|
|
|
module AMA |
|
8
|
|
|
module Entity |
|
9
|
|
|
class Mapper |
|
10
|
|
|
class Engine |
|
11
|
|
|
class Denormalizer |
|
12
|
|
|
# Denormalizer for non-standard objects not registered as entities |
|
13
|
|
|
class Enumerable |
|
14
|
|
|
include ::AMA::Entity::Mapper::Mixin::Reflection |
|
15
|
|
|
include ::AMA::Entity::Mapper::Mixin::Errors |
|
16
|
|
|
|
|
17
|
|
|
# @param [AMA::Entity::Mapper::Type::Concrete] type |
|
18
|
|
|
def supports(type) |
|
19
|
|
|
type.type.included_modules.include?(::Enumerable) |
|
20
|
|
|
end |
|
21
|
|
|
|
|
22
|
|
|
# @param [Object] source |
|
23
|
|
|
# @param [AMA::Entity::Mapper::Engine::Context] _context |
|
24
|
|
|
# @param [AMA::Entity::Mapper::Type::Concrete] target_type |
|
25
|
|
|
def denormalize(source, _context, target_type) |
|
26
|
|
|
return source if source.is_a?(target_type.type) |
|
27
|
|
|
# TODO: this is cool and would probably work, however, provided |
|
28
|
|
|
# factory should be used instead |
|
29
|
|
|
target_type.type.new(source) |
|
30
|
|
|
rescue ArgumentError => e |
|
31
|
|
|
message = "Failed to instantiate #{target_type}: #{e.message}." \ |
|
32
|
|
|
'Does it follow standard convention accepting enumerable as ' \ |
|
33
|
|
|
'#initialize() argument?' |
|
34
|
|
|
mapping_error(message, nil) |
|
35
|
|
|
rescue StandardError => e |
|
36
|
|
|
mapping_error("Failed to instantiate #{target_type}", e) |
|
37
|
|
|
end |
|
38
|
|
|
|
|
39
|
|
|
private |
|
40
|
|
|
|
|
41
|
|
|
def instantiate(type) |
|
42
|
|
|
type.type.new |
|
43
|
|
|
rescue ArgumentError => e |
|
44
|
|
|
message = "Failed to instantiate object of type #{type}: " \ |
|
45
|
|
|
"#{e.message}. Have you passed class with " \ |
|
46
|
|
|
'mandatory parameters in #initialize method?' |
|
47
|
|
|
mapping_error(message, nil) |
|
48
|
|
|
rescue StandardError => e |
|
49
|
|
|
message = "Failed to instantiate object of type #{type}" |
|
50
|
|
|
mapping_error(message, e) |
|
51
|
|
|
end |
|
52
|
|
|
end |
|
53
|
|
|
end |
|
54
|
|
|
end |
|
55
|
|
|
end |
|
56
|
|
|
end |
|
57
|
|
|
end |
|
58
|
|
|
|