Module: Searchgasm::CoreExt::Hash
- Defined in:
- lib/searchgasm/core_ext/hash.rb
Instance Method Summary collapse
- #deep_delete(value) ⇒ Object
- #deep_delete_duplicate_keys(hash) ⇒ Object
- #deep_dup ⇒ Object
- #deep_merge(other_hash) ⇒ Object
-
#deep_merge!(other_hash) ⇒ Object
Returns a new hash with
self
andother_hash
merged recursively. -
#fast_assert_valid_keys(valid_keys) ⇒ Object
assert_valid_keys was killing performance.
Instance Method Details
#deep_delete(value) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/searchgasm/core_ext/hash.rb', line 32 def deep_delete(value) case value when Array value.each { |v| deep_delete(v) } when Hash value.each do |k, v| next unless self[k].is_a?(Hash) case v when Hash, Array self[k].deep_delete(v) when String, Symbol self[k].delete(v) end end when String, Symbol delete(value) end end |
#deep_delete_duplicate_keys(hash) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/searchgasm/core_ext/hash.rb', line 19 def deep_delete_duplicate_keys(hash) hash.each do |k, v| if v.is_a?(Hash) && self[k] self[k].deep_delete_duplicate_keys(v) delete(k) if self[k].blank? else delete(k) end end self end |
#deep_dup ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/searchgasm/core_ext/hash.rb', line 4 def deep_dup new_hash = {} self.each do |k, v| case v when Hash new_hash[k] = v.deep_dup else new_hash[k] = v end end new_hash end |
#deep_merge(other_hash) ⇒ Object
52 53 54 55 56 57 58 |
# File 'lib/searchgasm/core_ext/hash.rb', line 52 def deep_merge(other_hash) self.merge(other_hash) do |key, oldval, newval| oldval = oldval.to_hash if oldval.respond_to?(:to_hash) newval = newval.to_hash if newval.respond_to?(:to_hash) oldval.class.to_s == 'Hash' && newval.class.to_s == 'Hash' ? oldval.deep_merge(newval) : newval end end |
#deep_merge!(other_hash) ⇒ Object
Returns a new hash with self
and other_hash
merged recursively. Modifies the receiver in place.
62 63 64 |
# File 'lib/searchgasm/core_ext/hash.rb', line 62 def deep_merge!(other_hash) replace(deep_merge(other_hash)) end |
#fast_assert_valid_keys(valid_keys) ⇒ Object
assert_valid_keys was killing performance. Array.flatten was the culprit, so I rewrote this method, got a 35% performance increase
67 68 69 70 |
# File 'lib/searchgasm/core_ext/hash.rb', line 67 def fast_assert_valid_keys(valid_keys) unknown_keys = keys - valid_keys raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty? end |