1
|
|
|
# frozen_string_literal: true |
2
|
|
|
|
3
|
|
|
require_relative '../../mixin/reflection' |
4
|
|
|
require_relative '../../mixin/errors' |
5
|
|
|
|
6
|
|
|
module AMA |
7
|
|
|
module Entity |
8
|
|
|
class Mapper |
9
|
|
|
module Handler |
10
|
|
|
module Entity |
11
|
|
|
# Default normalization handler |
12
|
|
|
class Normalizer |
13
|
|
|
include Mixin::Reflection |
14
|
|
|
|
15
|
|
|
INSTANCE = new |
16
|
|
|
|
17
|
|
|
# @param [Object] entity |
18
|
|
|
# @param [AMA::Entity::Mapper::Type] type |
19
|
|
|
# @param [AMA::Entity::Mapper::Context] _context |
20
|
|
|
def normalize(entity, type, _context = nil) |
21
|
|
|
type.attributes.values.each_with_object({}) do |attribute, data| |
22
|
|
|
next if attribute.virtual || attribute.sensitive |
23
|
|
|
data[attribute.name] = object_variable(entity, attribute.name) |
24
|
|
|
end |
25
|
|
|
end |
26
|
|
|
|
27
|
|
|
class << self |
28
|
|
|
include Mixin::Reflection |
29
|
|
|
|
30
|
|
|
# @param [Normalizer] implementation |
31
|
|
|
# @return [Normalizer] |
32
|
|
View Code Duplication |
def wrap(implementation) |
|
|
|
|
33
|
|
|
handler = handler_factory(implementation, INSTANCE) |
34
|
|
|
description = "Safety wrapper for #{implementation}" |
35
|
|
|
wrapper = method_object(:normalize, to_s: description, &handler) |
36
|
|
|
wrapper.singleton_class.instance_eval do |
37
|
|
|
include Mixin::Errors |
38
|
|
|
end |
39
|
|
|
wrapper |
40
|
|
|
end |
41
|
|
|
|
42
|
|
|
private |
43
|
|
|
|
44
|
|
|
# @param [Normalizer] impl |
45
|
|
|
# @param [Normalizer] fallback |
46
|
|
|
# @return [Proc] |
47
|
|
|
def handler_factory(impl, fallback) |
48
|
|
|
lambda do |entity, type, ctx| |
49
|
|
|
begin |
50
|
|
|
impl.normalize(entity, type, ctx) do |e, t, c| |
51
|
|
|
fallback.normalize(e, t, c) |
52
|
|
|
end |
53
|
|
|
rescue StandardError => e |
54
|
|
|
raise_if_internal(e) |
55
|
|
|
message = "Unexpected error from normalizer #{impl}" |
56
|
|
|
signature = '(entity, type, context)' |
57
|
|
|
options = { parent: e, context: ctx, signature: signature } |
58
|
|
|
compliance_error(message, **options) |
59
|
|
|
end |
60
|
|
|
end |
61
|
|
|
end |
62
|
|
|
end |
63
|
|
|
end |
64
|
|
|
end |
65
|
|
|
end |
66
|
|
|
end |
67
|
|
|
end |
68
|
|
|
end |
69
|
|
|
|