Sha256: d2804f2c1f4eea2ae833fc4e0de80de5cdbe9bdde19e1d2c19a92d69c5da465d

Contents?: true

Size: 1.41 KB

Versions: 7

Compression:

Stored size: 1.41 KB

Contents

module GetaroundUtils; end
module GetaroundUtils::Utils; end

module GetaroundUtils::Utils::DeepKeyValue
  def self.serialize(data)
    case data
    when Array
      flattify(data).map { |key, value| "#{key}=#{value}" }.join(' ')
    when Hash
      flattify(data).map { |key, value| "#{key}=#{value}" }.join(' ')
    when Numeric
      data.to_s
    when String
      data =~ /^".*"$/ ? data : data.inspect
    else
      data.to_s.inspect
    end
  end

  # https://stackoverflow.com/questions/48836464/how-to-flatten-a-hash-making-each-key-a-unique-value
  def self.flattify(value, result = {}, path = [], max_length = 512, max_depth = 5)
    if path.length > max_depth
      result[path.join(".")] = '"..."'
      return result
    end
    case value
    when Array
      value.each.with_index(0) do |v, i|
        flattify(v, result, path + [i], max_length, max_depth)
      end
    when Hash
      value.each do |k, v|
        flattify(v, result, path + [k], max_length, max_depth)
      end
    when Numeric
      result[path.join(".")] = value.to_s
    when String
      value = if value =~ /^".*"$/
        value.length >= max_length ? %{#{value[0...max_length]} ..."} : value
      else
        value.length >= max_length ? %{#{value[0...max_length]} ...}.inspect : value.inspect
      end
      result[path.join(".")] = value
    else
      flattify(value.to_s, result, path, max_length, max_depth)
    end
    result
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
getaround_utils-0.1.19 lib/getaround_utils/utils/deep_key_value.rb
getaround_utils-0.1.18 lib/getaround_utils/utils/deep_key_value.rb
getaround_utils-0.1.17 lib/getaround_utils/utils/deep_key_value.rb
getaround_utils-0.1.15 lib/getaround_utils/utils/deep_key_value.rb
getaround_utils-0.1.14 lib/getaround_utils/utils/deep_key_value.rb
getaround_utils-0.1.13 lib/getaround_utils/utils/deep_key_value.rb
getaround_utils-0.1.12 lib/getaround_utils/utils/deep_key_value.rb