1
|
|
|
# frozen_string_literal: true |
2
|
|
|
|
3
|
|
|
require_relative 'errors' |
4
|
|
|
|
5
|
|
|
module AMA |
6
|
|
|
module Entity |
7
|
|
|
class Mapper |
8
|
|
|
module Mixin |
9
|
|
|
# Collection of common methods twiddling with object internals |
10
|
|
|
module Reflection |
11
|
|
|
include Errors |
12
|
|
|
|
13
|
|
|
# @param [Object] object |
14
|
|
|
# @param [String, Symbol] name |
15
|
|
|
# @param [Object] value |
16
|
|
|
def set_object_attribute(object, name, value) |
17
|
|
|
method = "#{name}=" |
18
|
|
|
return object.send(method, value) if object.respond_to?(method) |
19
|
|
|
object.instance_variable_set("@#{name}", value) |
20
|
|
|
rescue StandardError => e |
21
|
|
|
message = "Failed to set attribute #{name} on #{object.class}, " \ |
22
|
|
|
"this is most likely due to `#{method}` method not following " \ |
23
|
|
|
'accessor conventions' |
24
|
|
|
mapping_error(message, parent: e) |
25
|
|
|
end |
26
|
|
|
|
27
|
|
|
# @param [Object] object |
28
|
|
|
def object_variables(object) |
29
|
|
|
intermediate = object.instance_variables.map do |variable| |
30
|
|
|
[variable[1..-1].to_sym, object.instance_variable_get(variable)] |
31
|
|
|
end |
32
|
|
|
Hash[intermediate] |
33
|
|
|
end |
34
|
|
|
|
35
|
|
|
# @param [Object] object |
36
|
|
|
# @param [String, Symbol] name |
37
|
|
|
def object_variable(object, name) |
38
|
|
|
name = "@#{name}" unless name[0] == '@' |
39
|
|
|
object.instance_variable_get(name) |
40
|
|
|
end |
41
|
|
|
|
42
|
|
|
def object_variable_exists(object, name) |
43
|
|
|
object.instance_variables.include?("@#{name}".to_sym) |
44
|
|
|
end |
45
|
|
|
|
46
|
|
|
def install_object_method(object, name, handler) |
47
|
|
|
compliance_error('Handler not provided') unless handler |
48
|
|
|
object.define_singleton_method(name, &handler) |
49
|
|
|
object |
50
|
|
|
end |
51
|
|
|
|
52
|
|
|
def method_object(method, to_s: nil, &handler) |
53
|
|
|
object = install_object_method(Object.new, method, handler) |
54
|
|
|
unless to_s |
55
|
|
|
to_s = "Wrapper object for proc #{handler} " \ |
56
|
|
|
"(installed as method :#{method})" |
57
|
|
|
end |
58
|
|
|
object.define_singleton_method(:to_s) do |
59
|
|
|
to_s |
60
|
|
|
end |
61
|
|
|
object |
62
|
|
|
end |
63
|
|
|
end |
64
|
|
|
end |
65
|
|
|
end |
66
|
|
|
end |
67
|
|
|
end |
68
|
|
|
|