Module: Mongrep::CoreExt::Hash

Defined in:
lib/mongrep/core_ext/hash.rb

Overview

Core extensions to Hash class

Instance Method Summary collapse

Instance Method Details

#slice_with_dot_notation(*keys) ⇒ {String => Object}

Produces a hash containing only given keys which can be in dot notation

Examples:

hash = { foo: { bar: 'foobar' }, bar: 'foo' }
hash.slice_with_dot_notation('foo.bar')
#=> { 'foo.bar' => 'foobar' }

Parameters:

  • keys (<String, Symbol>)

    the keys to include in the resulting hash. Note that they are stringified and self will be accessed with indifferent access.

Returns:

  • ({String => Object})

    the hash including only the selected stringified keys



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/mongrep/core_ext/hash.rb', line 20

def slice_with_dot_notation(*keys)
  keys.map(&:to_s).each_with_object(self.class.new) do |key, hash|
    path = key.to_s.split('.')

    catch :missing_key do
      hash[key] = path.reduce(with_indifferent_access) do |level, part|
        throw :missing_key unless level.key?(part)
        level[part]
      end
    end
  end
end