Class: Gitlab::ObjectifiedHash

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

Overview

Converts hashes to the objects.

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ ObjectifiedHash

Creates a new ObjectifiedHash object.



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

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, *args, &block) ⇒ Object (private)

Respond to messages for which ‘self.data` has a key



36
37
38
39
40
41
42
43
44
45
# File 'lib/gitlab/objectified_hash.rb', line 36

def method_missing(method_name, *args, &block)
  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, *args, &block)
  else
    super
  end
end

Instance Method Details

#[](key) ⇒ Object



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

def [](key)
  data[key]
end

#inspectString

Returns Formatted string with the class name, object id and original hash.

Returns:

  • (String)

    Formatted string with the class name, object id and original hash.



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

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

#to_hashHash Also known as: to_h

Returns The original hash.

Returns:

  • (Hash)

    The original hash.



17
18
19
# File 'lib/gitlab/objectified_hash.rb', line 17

def to_hash
  hash
end