Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/soaspec/hash_methods.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



5
6
7
8
9
# File 'lib/soaspec/hash_methods.rb', line 5

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)

    within hash to iterate through



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/soaspec/hash_methods.rb', line 52

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'
      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



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/soaspec/hash_methods.rb', line 16

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

#include_key?(key) ⇒ Boolean

Whether key is present at least once

Returns:

  • (Boolean)


45
46
47
48
# File 'lib/soaspec/hash_methods.rb', line 45

def include_key?(key)
  result = find_all_values_for key
  result != []
end

#include_value?(value) ⇒ Boolean

Value present in nested Hash.

Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/soaspec/hash_methods.rb', line 29

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/hash_methods.rb', line 12

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