Class: Pakyow::Support::IndifferentHash

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/pakyow/support/indifferentize.rb

Overview

Creates a Hash-like object can access stored data with symbol or

string keys.

The original hash is converted to symbol keys, which means

that a hash that originally contains a symbol and string key
with the same symbold value will conflict. It is not guaranteed
which value will be saved.

IndifferentHash instances have the same api as Hash, but any method

that would return a Hash, will return an IndifferentHash (with
the exception of to_h/to_hash).

NOTE: Please lookup Ruby’s documentation for Hash to learn what

methods are available.

Examples:

{ test: "test1", "test" => "test2" } => { test: "test2" }

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ IndifferentHash

Returns a new instance of IndifferentHash.



103
104
105
# File 'lib/pakyow/support/indifferentize.rb', line 103

def initialize(hash = {})
  self.internal_hash = hash
end

Class Method Details

.deep(object) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/pakyow/support/indifferentize.rb', line 27

def deep(object)
  hash = object.to_h
  unless hash.empty?
    hash = hash.each_with_object({}) { |(key, value), new_hash|
      new_hash[key] = case value
      when Hash
        deep(value)
      when Array
        value.map { |value_item|
          case value_item
          when Hash
            deep(value_item)
          else
            value_item
          end
        }
      else
        value
      end
    }
  end

  self.new(hash)
end

Instance Method Details

#internal_hashObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



114
115
116
# File 'lib/pakyow/support/indifferentize.rb', line 114

def internal_hash
  __getobj__
end

#pp(*args) ⇒ Object

Fixes an issue using pp inside a delegator.



141
142
143
# File 'lib/pakyow/support/indifferentize.rb', line 141

def pp(*args)
  Kernel.pp(*args)
end

#to_hObject Also known as: to_hash



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/pakyow/support/indifferentize.rb', line 118

def to_h
  internal_hash.each_with_object({}) { |(key, value), new_hash|
    key = case key
    when String
      key.to_sym
    else
      key
    end

    value = case value
    when IndifferentHash
      value.to_h
    else
      value
    end

    new_hash[key] = value
  }
end