Module: AMA::Entity::Mapper::Mixin::Reflection
- Includes:
- Errors
- Included in:
- Context, DSL::ClassMethods, Handler::Attribute::Validator, Handler::Entity::Denormalizer, Handler::Entity::Denormalizer, Handler::Entity::Enumerator, Handler::Entity::Enumerator, Handler::Entity::Factory, Handler::Entity::Injector, Handler::Entity::Injector, Handler::Entity::Normalizer, Handler::Entity::Normalizer, Handler::Entity::Validator, Type, Type::Attribute
- Defined in:
- lib/ama-entity-mapper/mixin/reflection.rb
Overview
Collection of common methods twiddling with object internals
Instance Method Summary
collapse
Methods included from Errors
#compliance_error, #mapping_error, #raise_if_internal, #validation_error
Instance Method Details
#install_object_method(object, name, handler) ⇒ Object
46
47
48
49
50
|
# File 'lib/ama-entity-mapper/mixin/reflection.rb', line 46
def install_object_method(object, name, handler)
compliance_error('Handler not provided') unless handler
object.define_singleton_method(name, &handler)
object
end
|
#method_object(method, to_s: nil, &handler) ⇒ Object
52
53
54
55
56
57
58
59
60
61
62
|
# File 'lib/ama-entity-mapper/mixin/reflection.rb', line 52
def method_object(method, to_s: nil, &handler)
object = install_object_method(Object.new, method, handler)
unless to_s
to_s = "Wrapper object for proc #{handler} " \
"(installed as method :#{method})"
end
object.define_singleton_method(:to_s) do
to_s
end
object
end
|
#object_variable(object, name) ⇒ Object
37
38
39
40
|
# File 'lib/ama-entity-mapper/mixin/reflection.rb', line 37
def object_variable(object, name)
name = "@#{name}" unless name[0] == '@'
object.instance_variable_get(name)
end
|
#object_variable_exists(object, name) ⇒ Object
42
43
44
|
# File 'lib/ama-entity-mapper/mixin/reflection.rb', line 42
def object_variable_exists(object, name)
object.instance_variables.include?("@#{name}".to_sym)
end
|
#object_variables(object) ⇒ Object
28
29
30
31
32
33
|
# File 'lib/ama-entity-mapper/mixin/reflection.rb', line 28
def object_variables(object)
intermediate = object.instance_variables.map do |variable|
[variable[1..-1].to_sym, object.instance_variable_get(variable)]
end
Hash[intermediate]
end
|
#set_object_attribute(object, name, value) ⇒ Object
16
17
18
19
20
21
22
23
24
25
|
# File 'lib/ama-entity-mapper/mixin/reflection.rb', line 16
def set_object_attribute(object, name, value)
method = "#{name}="
return object.send(method, value) if object.respond_to?(method)
object.instance_variable_set("@#{name}", value)
rescue StandardError => e
message = "Failed to set attribute #{name} on #{object.class}, " \
"this is most likely due to `#{method}` method not following " \
'accessor conventions'
mapping_error(message, parent: e)
end
|