Completed
Push — dev ( ffd8f7...ec8098 )
by Fike
51s
created

Reflection.object_variables()   A

Complexity

Conditions 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
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
          # @deprecated
14
          def populate_object(object, values)
15
            set_object_attributes(object, values)
16
          end
17
18
          def set_object_attributes(object, values)
19
            values.each do |attribute, value|
20
              set_object_attribute(object, attribute, value)
21
            end
22
            object
23
          end
24
25
          # @param [Object] object
26
          # @param [String, Symbol] name
27
          # @param [Object] value
28
          def set_object_attribute(object, name, value)
29
            method = "#{name}="
30
            return object.send(method, value) if object.respond_to?(method)
31
            object.instance_variable_set("@#{name}", value)
32
          rescue StandardError => e
33
            message = "Failed to set attribute #{name} on #{object.class}"
34
            mapping_error(message, e)
35
          end
36
37
          # @param [Object] object
38
          def object_variables(object)
39
            intermediate = object.instance_variables.map do |variable|
40
              [variable[1..-1].to_sym, object.instance_variable_get(variable)]
41
            end
42
            Hash[intermediate]
43
          end
44
45
          # @param [Object] object
46
          # @param [String, Symbol] name
47
          def object_variable(object, name)
48
            name = "@#{name}" unless name[0] == '@'
49
            object.instance_variable_get(name)
50
          end
51
        end
52
      end
53
    end
54
  end
55
end
56