Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/soaspec/core_ext/hash.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
.transform_keys_to_symbols(value) ⇒ Object
7 8 9 10 11 |
# File 'lib/soaspec/core_ext/hash.rb', line 7 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
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/soaspec/core_ext/hash.rb', line 62 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
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/soaspec/core_ext/hash.rb', line 18 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_key?(key) ⇒ Boolean
Whether key is present at least once
55 56 57 58 |
# File 'lib/soaspec/core_ext/hash.rb', line 55 def include_key?(key) result = find_all_values_for key result != [] end |
#include_value?(value) ⇒ Boolean
Value present in nested Hash.
39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/soaspec/core_ext/hash.rb', line 39 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
14 15 16 |
# File 'lib/soaspec/core_ext/hash.rb', line 14 def transform_keys_to_symbols inject({}){|memo, (k, v)| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); memo} end |