Module: HashExtension

Defined in:
lib/hash_extension.rb

Overview

Constant Summary collapse

NOT_PRESENT =
:symbol_for_non_present

Instance Method Summary collapse

Instance Method Details

#deep_fetch(*keys, default: NOT_PRESENT, &block) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/hash_extension.rb', line 6

def deep_fetch(*keys, default: NOT_PRESENT, &block)
  keys.reduce(self) do |obj, arg|
    begin
      arg = Integer(arg) if obj.is_a? Array
      obj.fetch(arg)
    rescue => e
      break block.call(arg) if block
      if default.nil?
        nil
      elsif default == NOT_PRESENT
        raise KeyError, "Could not fetch keypath (#{keys.join('.')}) at #{arg}", e.backtrace
      else
        default
      end
    end
  end
end

#fetch_keypath(keypath, default: NOT_PRESENT) ⇒ Object



24
25
26
# File 'lib/hash_extension.rb', line 24

def fetch_keypath(keypath, default: NOT_PRESENT)
  deep_fetch(*keypath.split('.'), default: default)
end