Module: EasyFormat::Hash

Defined in:
lib/easy_format/data_type_helper.rb

Class Method Summary collapse

Class Method Details

.any?(hash, &block) ⇒ Boolean

Evaluates the block on every key pair recursively. If any block is truthy, the method returns true, otherwise, false.



37
38
39
40
41
42
43
44
45
46
# File 'lib/easy_format/data_type_helper.rb', line 37

def any?(hash, &block)
  EasyFormat::Hash.log_deprecation('EasyFormat::Hash', __method__)
  raise 'hash is a required argument' if hash.nil?
  raise 'A block must be provided to this method to evaluate on each key pair. The evaluation occurs recursively. Block arguments: |k, v|' if block.nil?
  hash.each do |k, v|
    return true if yield(k, v)
    return true if v.is_a?(::Hash) && any?(v, &block) # recurse
  end
  false
end

.deep_sort(hash, include_arrays: true) ⇒ Object

Sorts by key recursively - optionally include sorting of arrays



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/easy_format/data_type_helper.rb', line 49

def deep_sort(hash, include_arrays: true)
  EasyFormat::Hash.log_deprecation('EasyFormat::Hash', __method__)
  raise "argument must be of type Hash - Actual type: #{hash.class}" unless hash.is_a?(::Hash)
  hash.each_with_object({}) do |(k, v), child_hash|
    child_hash[k] = case v
                    when ::Hash
                      deep_sort(v)
                    when ::Array
                      include_arrays ? v.sort : v
                    else
                      v
                    end
  end.sort.to_h
end

.log_deprecation(namespace, method_name) ⇒ Object



7
8
9
# File 'lib/easy_format/data_type_helper.rb', line 7

def log_deprecation(namespace, method_name)
  EasyIO.logger.warn "#{namespace}.#{method_name} is deprecated! Use Hashly.#{method_name} instead (require hashly)!"
end

.safe_value(hash, *keys) ⇒ Object



11
12
13
14
15
16
# File 'lib/easy_format/data_type_helper.rb', line 11

def safe_value(hash, *keys)
  EasyFormat::Hash.log_deprecation('EasyFormat::Hash', __method__)
  return nil if hash.nil? || hash[keys.first].nil?
  return hash[keys.first] if keys.length == 1 # return the value if we have reached the final key
  safe_value(hash[keys.shift], *keys) # recurse until we have reached the final key
end

.stringify_all_keys(hash) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/easy_format/data_type_helper.rb', line 18

def stringify_all_keys(hash)
  EasyFormat::Hash.log_deprecation('EasyFormat::Hash', __method__)
  stringified_hash = {}
  hash.each do |k, v|
    stringified_hash[k.to_s] = v.is_a?(::Hash) ? stringify_all_keys(v) : v
  end
  stringified_hash
end

.symbolize_all_keys(hash) ⇒ Object



27
28
29
30
31
32
33
34
# File 'lib/easy_format/data_type_helper.rb', line 27

def symbolize_all_keys(hash)
  EasyFormat::Hash.log_deprecation('EasyFormat::Hash', __method__)
  symbolized_hash = {}
  hash.each do |k, v|
    symbolized_hash[k.to_sym] = v.is_a?(::Hash) ? symbolize_all_keys(v) : v
  end
  symbolized_hash
end