Class: Darthjee::CoreExt::Hash::ChainFetcher Private

Inherits:
Object
  • Object
show all
Defined in:
lib/darthjee/core_ext/hash/chain_fetcher.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Class responsible for running ::Hash#chain_fetch

See Also:

Author:

  • Darthjee

Instance Method Summary collapse

Constructor Details

#initialize(hash, *keys, &block) ⇒ ChainFetcher

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of ChainFetcher.

Parameters:

  • hash (::Hash)

    Hash to fetch from

  • keys (Array)

    List of keys to fetch in chain

  • block (Proc)

    Block to call in case of missing key



17
18
19
20
21
# File 'lib/darthjee/core_ext/hash/chain_fetcher.rb', line 17

def initialize(hash, *keys, &block)
  @hash = hash
  @keys = keys
  @block = block
end

Instance Method Details

#fetchObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Crawls through the hash fetching the keys in chain

Examples:

hash = {
  a: {
    b: { c: 1, d: 2 }
  }
}

hash.chain_fetch(:a, :b, :c) # returns 1
hash.chain_fetch(:a, :c, :d) # raises KeyError
hash.chain_fetch(:a, :c, :d) { 10 } # returns 10
hash.chain_fetch(:a, :c, :d) { |key, _| key } # returns :c
hash.chain_fetch(:a, :c, :d) { |_, missing| missing } # returns [:d]

Returns:

  • (Object)

    value fetched from hash



28
29
30
31
32
# File 'lib/darthjee/core_ext/hash/chain_fetcher.rb', line 28

def fetch
  return fetch_with_block if block.present?

  fetch_without_block
end