Class: Yes::Core::Utils::HashUtils

Inherits:
Object
  • Object
show all
Defined in:
lib/yes/core/utils/hash_utils.rb

Overview

Utility class for deep hash operations

Class Method Summary collapse

Class Method Details

.deep_dup(hash) ⇒ Hash, Object

Returns a deep duplicate of a hash, recursively duplicating nested hashes.

Examples:

HashUtils.deep_dup({ a: { b: 1 } })
# => { a: { b: 1 } } (a completely independent copy)

Parameters:

  • hash (Hash)

    the hash to deep duplicate

Returns:

  • (Hash, Object)

    the deep duplicated hash, or the original object if not a Hash



17
18
19
20
21
22
23
# File 'lib/yes/core/utils/hash_utils.rb', line 17

def deep_dup(hash)
  return hash unless hash.instance_of?(Hash)

  dupl = hash.dup
  dupl.each { |k, v| dupl[k] = v.instance_of?(Hash) ? deep_dup(v) : v }
  dupl
end

.deep_flatten_hash(obj, prefix = nil, memo = {}) ⇒ Hash

Returns a hash with the keys flattened

Examples:

HashUtils.deep_flatten_hash({ name: 'A', otl_contexts: { root: { attr: 10, available: true } } })
 => {"name"=>"A", "otl_contexts.root.attr"=>10, "otl_contexts.root.available"=>true}

Parameters:

  • obj (Hash, Array)

    the object to flatten

  • prefix (String) (defaults to: nil)

    the key to use as a prefix for the keys in the hash

  • memo (Hash) (defaults to: {})

    the hash to store the flattened keys and values

Returns:

  • (Hash)

    the flattened hash



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/yes/core/utils/hash_utils.rb', line 35

def deep_flatten_hash(obj, prefix = nil, memo = {})
  case obj
  when Hash
    obj.each do |key, value|
      case [key, value]
      in Hash, Array
        memo[deep_flatten_hash(key)] = memo[deep_flatten_hash(value)]
      in String | Symbol, Hash
        deep_flatten_hash(value, prefix ? "#{prefix}.#{key}" : key.to_s, memo)
      in String | Symbol, Array
        memo[key.to_s] = deep_flatten_hash(value)
      in Array, _
        memo[deep_flatten_hash(key)] = deep_flatten_hash(value)
      else
        memo[prefix ? "#{prefix}.#{key}" : key.to_s] = value
      end
    end
    memo
  when Array
    obj.map { deep_flatten_hash(_1) }
  else
    obj
  end
end