Class: Gitlab::ObjectifiedHash

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/objectified_hash.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ ObjectifiedHash

Returns a new instance of ObjectifiedHash.



5
6
7
8
9
10
11
12
# File 'lib/gitlab/objectified_hash.rb', line 5

def initialize(hash)
  @hash = hash
  @data = hash.each_with_object({}) do |(key, value), data|
    value = self.class.new(value) if value.is_a?(Hash)
    value = value.map { |v| v.is_a?(Hash) ? self.class.new(v) : v } if value.is_a?(Array)
    data[key.to_s] = value
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name) ⇒ Object



29
30
31
32
33
34
35
36
37
38
# File 'lib/gitlab/objectified_hash.rb', line 29

def method_missing(method_name, *, &)
  if data.key?(method_name.to_s)
    data[method_name.to_s]
  elsif data.respond_to?(method_name)
    warn 'WARNING: Please convert ObjectifiedHash object to hash before calling Hash methods on it.'
    data.send(method_name, *, &)
  else
    super
  end
end

Instance Attribute Details

#data ⇒ Object (readonly)

Returns the value of attribute data.



27
28
29
# File 'lib/gitlab/objectified_hash.rb', line 27

def data
  @data
end

#hash ⇒ Object (readonly)

Returns the value of attribute hash.



27
28
29
# File 'lib/gitlab/objectified_hash.rb', line 27

def hash
  @hash
end

Instance Method Details

#[](key) ⇒ Object



23
24
25
# File 'lib/gitlab/objectified_hash.rb', line 23

def [](key)
  data[key]
end

#inspect ⇒ Object



19
20
21
# File 'lib/gitlab/objectified_hash.rb', line 19

def inspect
  "#<#{self.class}:#{object_id} {hash: #{hash.inspect}}"
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/gitlab/objectified_hash.rb', line 40

def respond_to_missing?(method_name, include_private = false)
  hash.keys.map(&:to_sym).include?(method_name.to_sym) || super
end

#to_hash ⇒ Object Also known as: to_h



14
15
16
# File 'lib/gitlab/objectified_hash.rb', line 14

def to_hash
  hash
end