2019-09-22 20:06:29 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Gitlab
|
|
|
|
module Utils
|
|
|
|
module InlineHash
|
|
|
|
extend self
|
|
|
|
|
|
|
|
# Transforms a Hash into an inline Hash by merging its nested keys.
|
|
|
|
#
|
|
|
|
# Input
|
|
|
|
#
|
|
|
|
# {
|
|
|
|
# 'root_param' => 'Root',
|
2019-10-01 02:06:13 -04:00
|
|
|
# 12 => 'number',
|
|
|
|
# symbol: 'symbol',
|
2019-09-22 20:06:29 -04:00
|
|
|
# nested_param: {
|
|
|
|
# key: 'Value'
|
|
|
|
# },
|
|
|
|
# 'very' => {
|
|
|
|
# 'deep' => {
|
|
|
|
# 'nested' => {
|
2019-10-01 02:06:13 -04:00
|
|
|
# 12 => 'Deep nested value'
|
2019-09-22 20:06:29 -04:00
|
|
|
# }
|
|
|
|
# }
|
|
|
|
# }
|
|
|
|
# }
|
|
|
|
#
|
|
|
|
#
|
|
|
|
# Result
|
|
|
|
#
|
|
|
|
# {
|
|
|
|
# 'root_param' => 'Root',
|
2019-10-01 02:06:13 -04:00
|
|
|
# 12 => 'number',
|
|
|
|
# symbol: symbol,
|
2019-09-22 20:06:29 -04:00
|
|
|
# 'nested_param.key' => 'Value',
|
2019-10-01 02:06:13 -04:00
|
|
|
# 'very.deep.nested.12' => 'Deep nested value'
|
2019-09-22 20:06:29 -04:00
|
|
|
# }
|
|
|
|
#
|
|
|
|
def merge_keys(hash, prefix: nil, connector: '.')
|
|
|
|
result = {}
|
2019-10-01 02:06:13 -04:00
|
|
|
pairs =
|
|
|
|
if prefix
|
|
|
|
base_prefix = "#{prefix}#{connector}"
|
|
|
|
hash.map { |key, value| ["#{base_prefix}#{key}", value] }
|
|
|
|
else
|
|
|
|
hash.to_a
|
|
|
|
end
|
2019-09-22 20:06:29 -04:00
|
|
|
|
|
|
|
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
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|