Sha256: 626d619e4374523da66ad7e4992c6d1d18b6ba66064cf7a91bcd7543a6b28999

Contents?: true

Size: 1.03 KB

Versions: 2

Compression:

Stored size: 1.03 KB

Contents

module GetaroundUtils; end
module GetaroundUtils::Utils; end

class GetaroundUtils::Utils::DeepKeyValueSerializer
  def 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 flattify(value, result = {}, path = [])
    case value
    when Array
      value.each.with_index(0) do |v, i|
        flattify(v, result, path + [i])
      end
    when Hash
      value.each do |k, v|
        flattify(v, result, path + [k])
      end
    when Numeric
      result[path.join(".")] = value.to_s
    when String
      result[path.join(".")] = value =~ /^".*"$/ ? value : value.inspect
    else
      result[path.join(".")] = value.to_s.inspect
    end
    result
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
getaround_utils-0.1.8 lib/getaround_utils/utils/deep_key_value_serializer.rb
getaround_utils-0.1.7 lib/getaround_utils/utils/deep_key_value_serializer.rb