Class: Hash

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

Overview

Override Hash class with convience methods

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



8
9
10
11
12
# File 'lib/soaspec/core_ext/hash.rb', line 8

def self.transform_keys_to_symbols(value)
  return value if not value.is_a?(Hash)
  hash = value.inject({}){|memo,(k,v)| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); memo}
  return 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

Parameters:

  • key (Key)

    Key within hash to iterate through



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

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



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

def find_all_values_for(key)
  result = []
  result << self[key]
  self.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.

Returns:

  • (Boolean)


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

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



15
16
17
# File 'lib/soaspec/core_ext/hash.rb', line 15

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