Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/soaspec/core_ext/hash.rb

Overview

Override Hash class with convience methods

Direct Known Subclasses

IndifferentHash

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.transform_keys_to_symbols(value) ⇒ Object

Transform each key in Hash to a symbol. Privately used by non-self method



4
5
6
7
8
9
# File 'lib/soaspec/core_ext/hash.rb', line 4

def self.transform_keys_to_symbols(value)
  return value unless value.is_a?(Hash)

  hash = value.each_with_object({}) { |(k, v), memo| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); }
  hash
end

Instance Method Details

#each_if_not_null(key) ⇒ Object

Loop through each item within a key within a Hash if the key exists



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/soaspec/core_ext/hash.rb', line 63

def each_if_not_null(key)
  case key.class.to_s
  when 'String'
    if self[key]
      self[key].each do |list_item|
        yield(list_item)
      end
    end
  when 'Array', 'Hash'
    if self[key[0]]
      if self[key[0]][key[1]]
        self[key[0]][key[1]].each do |list_item|
          yield(list_item)
        end
      end
    end
  end
end

#find_all_values_for(key) ⇒ Object

Returns all keys that have a particular value within a nested Hash



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/soaspec/core_ext/hash.rb', line 17

def find_all_values_for(key)
  result = []
  result << self[key]
  values.each do |hash_value|
    # next if hash_value.is_a? Array
    #
    if hash_value.is_a?(Array)
      hash_value.each do |array_element|
        result += array_element.find_all_values_for(key) if array_element.is_a? Hash
      end
    end

    values = [hash_value]
    values.each do |value|
      result += value.find_all_values_for(key) if value.is_a? Hash
    end
  end
  result.compact
end

#include_value?(value) ⇒ Boolean

Value present in nested Hash.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/soaspec/core_ext/hash.rb', line 38

def include_value?(value)
  each_value do |v|
    return true if v == value
    next unless v.is_a? Hash

    v.each_value do |v|
      return true if v == value
      next unless v.is_a? Hash

      v.each_value do |v|
        return true if v == value
      end
    end
  end
  false
end

#transform_keys_to_symbolsObject

Take keys of hash and transform those to a symbols



12
13
14
# File 'lib/soaspec/core_ext/hash.rb', line 12

def transform_keys_to_symbols
  each_with_object({}) { |(k, v), memo| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); }
end