Module: HashUtil

Defined in:
lib/hashutil.rb,
lib/hashutil/version.rb

Constant Summary collapse

VERSION =
IO.read(File.expand_path("../../../VERSION", __FILE__))

Class Method Summary collapse

Class Method Details

.make_proper_hash(hash_like) ⇒ Object

Converts a hash-like object to a proper hash using JSON.



48
49
50
# File 'lib/hashutil.rb', line 48

def self.make_proper_hash(hash_like)
  JSON.parse(JSON.generate(hash_like))
end

.multi_level_merge(h1, h2, options = {}) ⇒ Object

Merge multi-level hashes. Inspired by stackoverflow.com/questions/10691318/merge-some-complex-hashes-in-ruby

Available options:

:keys_to_strings - whether to convert all keys to strings


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/hashutil.rb', line 21

def self.multi_level_merge(h1, h2, options = {})
  original_options = options
  options = options.clone
  keys_to_strings = options.delete(:keys_to_strings)
  unless options.empty?
    raise "Invalid options: #{options}"
  end

  h1 ||= {}
  h2 ||= {}

  if keys_to_strings
    # Convert all keys to strings as requested.
    h1 = Hash[h1.collect { | k, v | [k.to_s, v] }]
    h2 = Hash[h2.collect { | k, v | [k.to_s, v] }]
  end

  h1.merge(h2) do |key, first, second|
    if first.is_a?(Hash) && second.is_a?(Hash)
      multi_level_merge(first, second, original_options)
    else
      second
    end
  end
end

.multi_level_sort_keys(obj) ⇒ Object

Sort hash keys (Ruby keeps track of key order in hashes).



6
7
8
9
10
11
12
13
14
# File 'lib/hashutil.rb', line 6

def self.multi_level_sort_keys(obj)
  if obj.is_a?(Hash)
    Hash[*obj.sort.map {|k, v| [k, multi_level_sort_keys(v)] }.flatten(1)]
  elsif obj.instance_of?(Array)
    obj.map {|element| multi_level_sort_keys(element) }
  else
    obj
  end
end