Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/soaspec/hash_methods.rb
Overview
Override Hash class with convience methods
Class Method Summary collapse
Instance Method Summary collapse
-
#each_if_not_null(key) ⇒ Object
Loop through each item within a key within a Hash if the key exists.
- #find_all_values_for(key) ⇒ Object
-
#include_key?(key) ⇒ Boolean
Whether key is present at least once.
-
#include_value?(value) ⇒ Boolean
Value present in nested Hash.
-
#transform_keys_to_symbols ⇒ Object
Take keys of hash and transform those to a symbols.
Class Method Details
Instance Method Details
#each_if_not_null(key) ⇒ Object
Loop through each item within a key within a Hash if the key exists
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
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.
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_symbols ⇒ Object
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 |