Module: PoroValidator::Utils::DeepFetch

Defined in:
lib/poro_validator/utils/deep_fetch.rb

Overview

Searches a deeply nested datastructure for a key path, and returns the associated value.

Examples:

fetches a value from a hash or deeply nested hash

options = { user: { location: { address: '123 Street' } } }
options.deep_fetch(:user, :location, :address) #=> '123 Street'

options.deep_fetch(:user, :non_existent_key) do
 'a value'
end #=> 'a value'

Returns:

  • associated value or if nil value from passed block.

Since:

  • 0.0.1

Defined Under Namespace

Classes: UndefinedPathError

Instance Method Summary collapse

Instance Method Details

#deep_fetch(*args, &block) ⇒ Object

Since:

  • 0.0.1



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/poro_validator/utils/deep_fetch.rb', line 21

def deep_fetch(*args, &block)
  args.reduce(self) do |obj, arg|
    begin
      arg = Integer(arg) if obj.is_a?(Array)
      obj.fetch(arg)
    rescue ArgumentError, IndexError, NoMethodError => e
      break block.call(arg) if block
      raise(
        UndefinedPathError,
        "Could not fetch path (#{args.join(' > ')}) at #{arg}",
        e.backtrace
      )
    end
  end
end