Class: Mj::HashUtils::KeyTransformer

Inherits:
Object
  • Object
show all
Defined in:
lib/mj/hash_utils/key_transformer.rb

Overview

:reek:TooManyStatements

Instance Method Summary collapse

Instance Method Details

#apply_to_collection(collection, &block) ⇒ Object



23
24
25
26
27
# File 'lib/mj/hash_utils/key_transformer.rb', line 23

def apply_to_collection(collection, &block)
  collection.map do |item|
    transform(item, &block)
  end
end

#deep_transform_keys(hash, &block) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/mj/hash_utils/key_transformer.rb', line 29

def deep_transform_keys(hash, &block)
  result = {}
  hash.each do |key, value|
    new_value = value.is_a?(::Hash) ? transform(value, &block) : value
    result[yield(key)] = new_value
  end
  result
end

#transform(item_or_collection, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/mj/hash_utils/key_transformer.rb', line 7

def transform(item_or_collection, &block)
  if item_or_collection.is_a?(Array)
    return apply_to_collection(item_or_collection, &block)
  end

  return item_or_collection unless item_or_collection.is_a?(::Hash)

  new_hash = deep_transform_keys(item_or_collection, &block)

  new_hash.each do |key, value|
    if value.is_a?(Array)
      new_hash[key] = transform(value, &block)
    end
  end
end