Module: Gitlab::Utils::InlineHash

Extended by:
InlineHash
Included in:
InlineHash
Defined in:
lib/gitlab/utils/inline_hash.rb

Instance Method Summary collapse

Instance Method Details

#merge_keys(hash, prefix: nil, connector: '.') ⇒ Object

Transforms a Hash into an inline Hash by merging its nested keys.

Input

{
  'root_param' => 'Root',
  12 => 'number',
  symbol: 'symbol',
  nested_param: {
    key: 'Value'
  },
  'very' => {
    'deep' => {
      'nested' => {
        12 => 'Deep nested value'
      }
    }
  }
}

Result

{
  'root_param' => 'Root',
   12 => 'number',
   symbol: symbol,
  'nested_param.key' => 'Value',
  'very.deep.nested.12' => 'Deep nested value'
}

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/gitlab/utils/inline_hash.rb', line 39

def merge_keys(hash, prefix: nil, connector: '.')
  result = {}
  pairs =
    if prefix
      base_prefix = "#{prefix}#{connector}"
      hash.map { |key, value| ["#{base_prefix}#{key}", value] }
    else
      hash.to_a
    end

  until pairs.empty?
    key, value = pairs.shift

    if value.is_a?(Hash)
      value.each { |k, v| pairs.unshift ["#{key}#{connector}#{k}", v] }
    else
      result[key] = value
    end
  end

  result
end