Module: LedgerSync::Util::HashHelpers

Defined in:
lib/ledger_sync/util/hash_helpers.rb

Class Method Summary collapse

Class Method Details

.deep_merge(hash_to_merge_into:, other_hash:, &block) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/ledger_sync/util/hash_helpers.rb', line 12

def deep_merge(hash_to_merge_into:, other_hash:, &block)
  hash_to_merge_into.merge(other_hash) do |key, this_val, other_val|
    if this_val.is_a?(Hash) && other_val.is_a?(Hash)
      deep_merge(hash_to_merge_into: this_val, other_hash: other_val, &block)
    elsif block_given?
      block.call(key, this_val, other_val)
    else
      other_val
    end
  end
end

.deep_stringify_keys(hash) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/ledger_sync/util/hash_helpers.rb', line 45

def deep_stringify_keys(hash)
  deep_transform_keys_in_object(hash) do |key|
    key.to_s
  rescue StandardError
    key
  end
end

.deep_symbolize_keys(hash) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/ledger_sync/util/hash_helpers.rb', line 24

def deep_symbolize_keys(hash)
  deep_transform_keys_in_object(hash) do |key|
    key.to_sym
  rescue StandardError
    key
  end
end

.deep_transform_keys_in_object(object, &block) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/ledger_sync/util/hash_helpers.rb', line 32

def deep_transform_keys_in_object(object, &block)
  case object
  when Hash
    object.each_with_object({}) do |(key, value), result|
      result[yield(key)] = deep_transform_keys_in_object(value, &block)
    end
  when Array
    object.map { |e| deep_transform_keys_in_object(e, &block) }
  else
    object
  end
end