Sha256: ae8746ab834ee51aef5eb65729e85d85ee7b032597b077517352ad8b67aac210

Contents?: true

Size: 1.09 KB

Versions: 1

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

module Darthjee
  module CoreExt
    module Hash
      # Class responsible for running ::Hash#chain_fetch
      #
      # @api private
      #
      # @see Darthjee::CoreExt::Hash#chain_fetch
      class ChainFetcher
        def initialize(hash, *keys, &block)
          @hash = hash
          @keys = keys
          @block = block
        end

        # Crawls through the hash fetching the keys in chain
        #
        # @example (see Darthjee::CoreExt::Hash#chain_fetch)
        #
        # @return [Object] value fetched from array
        def fetch
          block.present? ? fetch_with_block : fetch_without_block
        end

        private

        attr_reader :hash, :keys, :block

        def fetch_with_block
          @hash = hash.fetch(keys.shift) do |*args|
            missed_keys = keys
            @keys = []
            block.call(*(args + [missed_keys]))
          end until keys.empty?
          hash
        end

        def fetch_without_block
          @hash = hash.fetch(keys.shift) until keys.empty?
          hash
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
darthjee-core_ext-1.7.4 lib/darthjee/core_ext/hash/chain_fetcher.rb