Module: Blinkbox::ExtraHashMethods

Defined in:
lib/blinkbox/utilities/extra_hash_methods.rb

Instance Method Summary collapse

Instance Method Details

#shallow!(join = ".") ⇒ Boolean

Turns a deep/nested hash into a shallow one by concatenating nested key names.

@example: Removing nesting

hash = {
  "a" => {
    "1" => 'will be a.1'
  },
  "b" => 'will be b'
}
hash.extend(ExtraHashMethods).shallow!
# => true
p hash
# => { "a.1" => 'will be a.1', "b" => 'will be b' }

@example: Removing nesting - custom join string

hash = {
  "a" => {
    "1" => 'will be merged down'
  },
  "b" => 'will be the same'
}
hash.extend(ExtraHashMethods).shallow!("~")
# => true
p hash
# => { "a~1" => 'will be merged down', "b" => 'will be the same' }

@example: No removal needed

hash = {
  "a" => 'no deep keys here'
}
hash.extend(ExtraHashMethods).shallow!
# => false
p hash
# => { "a" => 'no deep keys here' }

@example: Conflicting key names

hash = {
  "a" => {
    "1" => 'will be a.1'
  },
  "a.1" => 'will be lost!'
}
hash.extend(ExtraHashMethods).shallow!
# => ["a.1"]
p hash
# => { "a.1" => 'will be a.1' }

Parameters:

  • join (String) (defaults to: ".")

    The string to use to join keys.

Returns:

  • (Boolean)

    Whether any keys were changed


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/blinkbox/utilities/extra_hash_methods.rb', line 52

def shallow!(join = ".")
  shallowed = false
  keys = self.keys.select { |k| self[k].is_a?(Hash) }
  while (k = keys.shift) do
    shallowed = shallowed || true
    v = self.delete(k)
    v.each do |sub_k, sub_v|
      new_key = [k, sub_k].join(join)
      if self.has_key?(new_key)
        shallowed = [] unless shallowed.is_a?(Array)
        shallowed.push(new_key)
      end
      self[new_key] = if sub_v.is_a?(Hash)
        sub_v.extend(ExtraHashMethods).shallow!(join)
        keys.push(new_key)
        sub_v
      else
        sub_v
      end
    end
  end
  shallowed
end