Module: HashExtension
- Defined in:
- lib/hash_extension.rb
Overview
Implementation based on blogpost: reedy.in/words/archive/2015/01/08/deep-fetch/ and hashie: github.com/intridea/hashie/blob/master/lib/hashie/extensions/deep_fetch.rb
Constant Summary collapse
- NOT_PRESENT =
:symbol_for_non_present
Instance Method Summary collapse
- #deep_fetch(*keys, default: NOT_PRESENT, &block) ⇒ Object
- #fetch_keypath(keypath, default: NOT_PRESENT) ⇒ Object
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 |