require "celsius" module Celsius::Hash # # This module provides some helper functions for dealing with hashes # def self.deep_find_key(object, key) results = [] if key.is_a?(Array) key.inject(object) do |memo, key_element| deep_find_key(memo, key_element) end else if object.is_a?(Array) # flatten(1) prevents unintend array nesting due to recursion results.concat object.map { |value| deep_find_key(value, key) }.flatten(1) elsif object.is_a?(Hash) if object.has_key?(key.to_s) || object.has_key?(key.to_sym) results << (object[key.to_s] || object[key.to_sym]) else # its easier to concat an empty array than checking for nil results.concat deep_find_key(object.values, key) || [] end end # remove nils results.compact! # in case nothing was found, return nil to ease detecting this case results.empty? ? nil : results end end def self.smart_fetch(hash, key) result = hash[key.to_s] result = hash[key.to_sym] if result.nil? end def self.smart_store(hash, key, value) if hash[key] unless hash[key].is_a?(Array) hash[key] = [hash[key]] end hash[key].push(value) else hash[key] = value end hash end end