module Hashie::Extensions::DeepGrep
Searches nested hashes and arrays for matching string and symbol keys or values.
@example Search a nested collection
hash = { people: [{ name: 'Ada' }] }.extend(Hashie::Extensions::DeepGrep) hash.deep_grep(/Ada/) # => [{ name: 'Ada' }]
Public Class Methods
deep_grep(pattern, object)
click to toggle source
Returns key/subtree pairs for matching keys, containing hashes for matching scalar values, and matching scalar array elements. Matching keys stop descent.
@example Search an array without extending it
Hashie::Extensions::DeepGrep.deep_grep(/Ada/, ['Ada', 'Grace']) # => ['Ada']
# File lib/hashie/extensions/deep_grep.rb, line 23 def self.deep_grep(pattern, object) raise ArgumentError, 'pattern must be a Regexp' unless pattern.is_a?(Regexp) search(pattern, object, [], {}.compare_by_identity) end
Private Class Methods
matches?(pattern, value)
click to toggle source
# File lib/hashie/extensions/deep_grep.rb, line 63 def self.matches?(pattern, value) (value.is_a?(String) || value.is_a?(Symbol)) && pattern.match?(value.to_s) end
search(pattern, object, results, ancestors)
click to toggle source
# File lib/hashie/extensions/deep_grep.rb, line 29 def self.search(pattern, object, results, ancestors) return results if ancestors.key?(object) || !(object.is_a?(::Hash) || object.is_a?(::Array)) ancestors[object] = true if object.is_a?(::Hash) search_hash(pattern, object, results, ancestors) else search_array(pattern, object, results, ancestors) end ancestors.delete(object) results end
search_array(pattern, object, results, ancestors)
click to toggle source
# File lib/hashie/extensions/deep_grep.rb, line 56 def self.search_array(pattern, object, results, ancestors) object.each do |value| matches?(pattern, value) ? results << value : search(pattern, value, results, ancestors) end end
search_hash(pattern, object, results, ancestors)
click to toggle source
# File lib/hashie/extensions/deep_grep.rb, line 44 def self.search_hash(pattern, object, results, ancestors) results << object if object.any? { |key, value| !matches?(pattern, key) && matches?(pattern, value) } object.each do |key, value| if matches?(pattern, key) results << { key => value } else search(pattern, value, results, ancestors) end end end
Public Instance Methods
deep_grep(pattern)
click to toggle source
@example Match a key and return its subtree
hash = { user: { name: 'Ada' } }.extend(Hashie::Extensions::DeepGrep) hash.deep_grep(/user/) # => [{ user: { name: 'Ada' } }]
# File lib/hashie/extensions/deep_grep.rb, line 14 def deep_grep(pattern) DeepGrep.deep_grep(pattern, self) end