Class: Google::HashUtils

Inherits:
Object
  • Object
show all
Defined in:
lib/google/hash_utils.rb

Overview

Helper class to process and mutate hashes.

Class Method Summary collapse

Class Method Details

.camelize_keys(source) ⇒ Object

Converts all keys to symbols



20
21
22
23
24
25
26
27
28
# File 'lib/google/hash_utils.rb', line 20

def self.camelize_keys(source)
  result = source.clone
  # rubocop:disable Performance/HashEachMethods
  result.keys.each do |k|
    result[Google::StringUtils.camelize(k.to_s)] = result.delete(k)
  end
  # rubocop:enable Performance/HashEachMethods
  result
end

Allows fetching objects within a tree path.



41
42
43
44
45
46
47
48
# File 'lib/google/hash_utils.rb', line 41

def self.navigate(source, path, default = nil)
  key = path.take(1)[0]
  path = path.drop(1)
  return default unless source.key?(key)
  result = source.fetch(key)
  return HashUtils.navigate(result, path, default) unless path.empty?
  return result if path.empty?
end

.path2navigate(path) ⇒ Object

Converts a path in the form a/b/c/d into %w(a b c d)



51
52
53
# File 'lib/google/hash_utils.rb', line 51

def self.path2navigate(path)
  "%w[#{path.split('/').join(' ')}]"
end

.symbolize_keys(source) ⇒ Object



30
31
32
33
34
35
36
37
38
# File 'lib/google/hash_utils.rb', line 30

def self.symbolize_keys(source)
  result = source.clone
  # rubocop:disable Performance/HashEachMethods
  result.keys.each do |k|
    result[Google::StringUtils.symbolize(k)] = result.delete(k)
  end
  # rubocop:enable Performance/HashEachMethods
  result
end