Sha256: 95b4ebce336f269ef1f3a7805a3cd3e0077c52dd7ae1aa9307b64568fb4786a1

Contents?: true

Size: 1.04 KB

Versions: 4

Compression:

Stored size: 1.04 KB

Contents

module Hashie
  module Extensions
    # Searches a deeply nested datastructure for a key path, and returns the associated value.
    #
    #  options = { user: { location: { address: '123 Street' } } }
    #  options.deep_fetch :user, :location, :address #=> '123 Street'
    #
    # If a block is provided its value will be returned if the key does not exist.
    #
    #  options.deep_fetch(:user, :non_existent_key) { 'a value' } #=> 'a value'
    #
    # This is particularly useful for fetching values from deeply nested api responses or params hashes.
    module DeepFetch
      class UndefinedPathError < StandardError; end

      def deep_fetch(*args, &block)
        args.reduce(self) do |obj, arg|
          begin
            arg = Integer(arg) if obj.kind_of? 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
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
hashie-3.1.0 lib/hashie/extensions/deep_fetch.rb
whos_dated_who-0.1.0 vendor/bundle/gems/hashie-3.0.0/lib/hashie/extensions/deep_fetch.rb
whos_dated_who-0.0.1 vendor/bundle/gems/hashie-3.0.0/lib/hashie/extensions/deep_fetch.rb
hashie-3.0.0 lib/hashie/extensions/deep_fetch.rb