Class: Custplace::MetaMethods

Inherits:
Object
  • Object
show all
Includes:
Memoizable
Defined in:
lib/custplace/meta_methods.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ MetaMethods

Returns a new instance of MetaMethods.



7
8
9
# File 'lib/custplace/meta_methods.rb', line 7

def initialize(data)
  @attrs = data.is_a?(Hash) ? data.with_indifferent_access : data
end

Instance Attribute Details

#attrsObject (readonly)

Returns the value of attribute attrs.



5
6
7
# File 'lib/custplace/meta_methods.rb', line 5

def attrs
  @attrs
end

#keysObject (readonly)

Returns the value of attribute keys.



5
6
7
# File 'lib/custplace/meta_methods.rb', line 5

def keys
  @keys
end

Class Method Details

.define_attribute_method(key1, klass = nil, method_alias: key1, target_alias: nil, include_keys: nil, extra_key: nil) ⇒ Object

Dynamically define a method for an attribute

Parameters:

  • , or [Array]

  • (defaults to: nil)
  • (defaults to: key1)
    • alias

  • (defaults to: nil)
    • key for this item in the target class

  • (defaults to: nil)
    • used in define_attribute_method not here

  • (defaults to: nil)
    • down an extra level. IE progression: { raids: […] }



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/custplace/meta_methods.rb', line 30

def define_attribute_method(key1, klass = nil, method_alias: key1, target_alias: nil, include_keys: nil, extra_key: nil)
  define_method(method_alias) do ||
    target = extra_key.nil? ? @attrs[key1] : @attrs[key1].nil? ? nil : @attrs[key1][extra_key]
    if target.nil?
      nil
    else
      if klass.nil?
        target
      else
        if klass.is_a?(Array)
          target.map do |t|
            klass.first.new(t)
          end
        else
          klass.new(target)
        end
      end
    end
  end
  begin
    return memoize(method_alias)
  rescue Exception => e
    Appsignal.send_error(e)
  end
end

.object_attr_reader(key1, klass = nil, **args) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/custplace/meta_methods.rb', line 12

def object_attr_reader(key1, klass=nil, **args)
  if key1.is_a?(Array)
    key1.each do |key|
      define_attribute_method(key, klass, args)
    end
  else
    define_attribute_method(key1, klass, args)
  end
end