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) |
21
|
|
|
type.attributes.values.each_with_object({}) do |attribute, data| |
22
|
|
|
next if attribute.virtual |
23
|
|
|
condition = context.include_sensitive_attributes |
24
|
|
|
next if attribute.sensitive && !condition |
25
|
|
|
data[attribute.name] = object_variable(entity, attribute.name) |
26
|
|
|
end |
27
|
|
|
end |
28
|
|
|
|
29
|
|
|
class << self |
30
|
|
|
include Mixin::Reflection |
31
|
|
|
|
32
|
|
|
# @param [Normalizer] implementation |
33
|
|
|
# @return [Normalizer] |
34
|
|
|
def wrap(implementation) |
35
|
|
|
handler = handler_factory(implementation, INSTANCE) |
36
|
|
|
description = "Safety wrapper for #{implementation}" |
37
|
|
|
wrapper = method_object(:normalize, to_s: description, &handler) |
38
|
|
|
wrapper.singleton_class.instance_eval do |
39
|
|
|
include Mixin::Errors |
40
|
|
|
end |
41
|
|
|
wrapper |
42
|
|
|
end |
43
|
|
|
|
44
|
|
|
private |
45
|
|
|
|
46
|
|
|
# @param [Normalizer] impl |
47
|
|
|
# @param [Normalizer] fallback |
48
|
|
|
# @return [Proc] |
49
|
|
|
def handler_factory(impl, fallback) |
50
|
|
|
lambda do |entity, type, ctx| |
51
|
|
|
begin |
52
|
|
|
impl.normalize(entity, type, ctx) do |e, t, c| |
53
|
|
|
fallback.normalize(e, t, c) |
54
|
|
|
end |
55
|
|
|
rescue StandardError => e |
56
|
|
|
raise_if_internal(e) |
57
|
|
|
message = "Unexpected error from normalizer #{impl}" |
58
|
|
|
signature = '(entity, type, context)' |
59
|
|
|
options = { parent: e, context: ctx, signature: signature } |
60
|
|
|
compliance_error(message, **options) |
61
|
|
|
end |
62
|
|
|
end |
63
|
|
|
end |
64
|
|
|
end |
65
|
|
|
end |
66
|
|
|
end |
67
|
|
|
end |
68
|
|
|
end |
69
|
|
|
end |
70
|
|
|
end |
71
|
|
|
|