Class: Grover::Utils

Inherits:
Object show all
Defined in:
lib/grover/utils.rb

Overview

Utility class for Grover helper methods

Class Method Summary collapse

Class Method Details

.deep_assign(hash, keys, value) ⇒ Object

Assign value to a hash using an array of keys to traverse



28
29
30
31
32
33
34
35
36
# File 'lib/grover/utils.rb', line 28

def self.deep_assign(hash, keys, value)
  if keys.length == 1
    hash[keys.first] = value
  else
    key = keys.shift
    hash[key] ||= {}
    deep_assign hash[key], keys, value
  end
end

.deep_merge!(hash, other_hash) ⇒ Object

Deep merge a hash with another hash

Based on active support

See Also:

  • active_support/core_ext/hash/deep_mergeactive_support/core_ext/hash/deep_merge.rb


70
71
72
73
74
75
76
77
78
# File 'lib/grover/utils.rb', line 70

def self.deep_merge!(hash, other_hash)
  hash.merge!(other_hash) do |_, this_val, other_val|
    if this_val.is_a?(Hash) && other_val.is_a?(Hash)
      deep_merge! this_val.dup, other_val
    else
      other_val
    end
  end
end

.deep_stringify_keys(hash) ⇒ Object

Deep transform the keys in the hash to strings



60
61
62
# File 'lib/grover/utils.rb', line 60

def self.deep_stringify_keys(hash)
  deep_transform_keys_in_object hash, &:to_s
end

.deep_transform_keys_in_object(object, &block) ⇒ Object

Deep transform the keys in an object (Hash/Array)

Copied from active support

See Also:

  • active_support/core_ext/hash/keysactive_support/core_ext/hash/keys.rb


44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/grover/utils.rb', line 44

def self.deep_transform_keys_in_object(object, &block)
  case object
  when Hash
    object.each_with_object({}) do |(key, value), result|
      result[yield(key)] = deep_transform_keys_in_object(value, &block)
    end
  when Array
    object.map { |e| deep_transform_keys_in_object(e, &block) }
  else
    object
  end
end

.normalize_object(object) ⇒ Object

Recursively normalizes hash objects with camelized string keys



83
84
85
# File 'lib/grover/utils.rb', line 83

def self.normalize_object(object)
  deep_transform_keys_in_object(object) { |k| normalize_key(k) }
end

.squish(string) ⇒ Object

Removes leading/trailing whitespaces and squishes inner whitespace with a single space

N.B. whitespace includes all ‘blank’ characters as well as newlines/carriage returns etc.



18
19
20
21
22
23
# File 'lib/grover/utils.rb', line 18

def self.squish(string)
  string.
    gsub(/\A[[:space:]]+/, '').
    gsub(/[[:space:]]+\z/, '').
    gsub(/[[:space:]]+/, ' ')
end