summaryrefslogtreecommitdiff
path: root/lib/hashie/extensions/deep_find.rb
blob: 0e77932f406a3d388254d4770b5dd654da1bb37d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
require 'hashie/extensions/deep_locate'
module Hashie
  module Extensions
    module DeepFind
      # Performs a depth-first search on deeply nested data structures for
      # a key and returns the first occurrence of the key.
      #
      #  options = {user: {location: {address: '123 Street'}}}
      #  options.extend(Hashie::Extensions::DeepFind)
      #  options.deep_find(:address) # => '123 Street'
      #
      #  class MyHash < Hash
      #    include Hashie::Extensions::DeepFind
      #  end
      #
      #  my_hash = MyHash.new
      #  my_hash[:user] = {location: {address: '123 Street'}}
      #  my_hash.deep_find(:address) # => '123 Street'
      def deep_find(key)
        _deep_find(key)
      end

      alias deep_detect deep_find

      # Performs a depth-first search on deeply nested data structures for
      # a key and returns all occurrences of the key.
      #
      #  options = {
      #    users: [
      #      { location: {address: '123 Street'} },
      #      { location: {address: '234 Street'}}
      #    ]
      #  }
      #  options.extend(Hashie::Extensions::DeepFind)
      #  options.deep_find_all(:address) # => ['123 Street', '234 Street']
      #
      #  class MyHash < Hash
      #    include Hashie::Extensions::DeepFind
      #  end
      #
      #  my_hash = MyHash.new
      #  my_hash[:users] = [
      #    {location: {address: '123 Street'}},
      #    {location: {address: '234 Street'}}
      #  ]
      #  my_hash.deep_find_all(:address) # => ['123 Street', '234 Street']
      def deep_find_all(key)
        matches = _deep_find_all(key)
        matches.empty? ? nil : matches
      end

      alias deep_select deep_find_all

      private

      def _deep_find(key, object = self)
        _deep_find_all(key, object).first
      end

      def _deep_find_all(key, object = self, matches = [])
        deep_locate_result = DeepLocate.deep_locate(key, object).tap do |result|
          result.map! { |element| element[key] }
        end

        matches.concat(deep_locate_result)
      end
    end
  end
end