Module: BB::Hash

Defined in:
lib/blackbox/hash.rb

Overview

Hash utilities.

Class Method Summary (collapse)

Class Method Details

+ (Hash) flatten_prop_style(input = {}, opts = {}, output = {})

Recursively flatten a hash to property-style format. This is a lossy conversion and should only be used for display-purposes.

Examples:

input = { :a => { :b => :c } }
BB::Hash.flatten_prop_style(input)
=> {"a.b"=>:c}
input = { :a => { :b => [:c, :d, :e] } }
BB::Hash.flatten_prop_style(input)
=> {"a.b"=>"c,d,e"}

Parameters:

  • input (Hash) (defaults to: {})

    Input hash

  • opts (Hash) (defaults to: {})

    Options

  • output (Hash) (defaults to: {})

    (leave this blank)

Options Hash (opts):

  • :delimiter (String)

    Key delimiter (Default: '.')

Returns:

  • (Hash)

    Output hash (flattened)



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/blackbox/hash.rb', line 33

def flatten_prop_style(input = {}, opts = {}, output = {})
  input.each do |key, value|
    key = opts[:prefix].nil? ? key.to_s : "#{opts[:prefix]}#{opts[:delimiter] || '.'}#{key}"
    case value
    when ::Hash
      flatten_prop_style(value, opts.merge(prefix: key), output)
    when Array
      output[key] = value.join(',')
    else
      output[key] = value
    end
  end
  output
end

+ (Hash) symbolize_keys(hash)

Symbolize all top level keys.

Parameters:

  • hash (Hash)

    Input hash

Returns:

  • (Hash)

    Output hash (with symbolized keys)



10
11
12
# File 'lib/blackbox/hash.rb', line 10

def symbolize_keys(hash)
  hash.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
end