lib/cliutils/ext/hash_extensions.rb in cliutils-1.2.4 vs lib/cliutils/ext/hash_extensions.rb in cliutils-1.2.5

- old
+ new

@@ -60,9 +60,36 @@ # @return [Hash] def deep_transform_keys!(&block) _deep_transform_keys_in_object!(self, &block) end + # Recursively searches a hash for the passed + # key and returns the value (if there is one). + # http://stackoverflow.com/a/2239847/327179 + # @param [<Symbol, String>] key The key to search for + # @return [Multiple] + def recursive_find_by_key(key) + # Create a stack of hashes to search through for the needle which + # is initially this hash + stack = [ self ] + + # So long as there are more haystacks to search... + while (to_search = stack.pop) + # ...keep searching for this particular key... + to_search.each do |k, v| + # ...and return the corresponding value if it is found. + return v if (k == key) + + # If this value can be recursively searched... + if (v.respond_to?(:recursive_find_by_key)) + # ...push that on to the list of places to search. + stack << v + end + end + end + yield if block_given? + end + private # Modification to deep_transform_keys that allows for # the existence of arrays. # https://github.com/rails/rails/pull/9720/files?short_path=4be3c90