Module: Darthjee::CoreExt::Hash

Includes:
Cameliazable, Changeable, KeyChangeable, Transformable, Transposeable
Included in:
Hash
Defined in:
lib/darthjee/core_ext/hash.rb,
lib/darthjee/core_ext/hash/squasher.rb,
lib/darthjee/core_ext/hash/changeable.rb,
lib/darthjee/core_ext/hash/key_changer.rb,
lib/darthjee/core_ext/hash/keys_sorter.rb,
lib/darthjee/core_ext/hash/cameliazable.rb,
lib/darthjee/core_ext/hash/chain_fetcher.rb,
lib/darthjee/core_ext/hash/transformable.rb,
lib/darthjee/core_ext/hash/transposeable.rb,
lib/darthjee/core_ext/hash/value_changer.rb,
lib/darthjee/core_ext/hash/key_changeable.rb,
lib/darthjee/core_ext/hash/deep_hash_constructor.rb,
lib/darthjee/core_ext/hash/deep_hash_constructor/setter.rb

Defined Under Namespace

Modules: Cameliazable, Changeable, KeyChangeable, Transformable, Transposeable Classes: ChainFetcher, DeepHashConstructor, KeyChanger, KeysSorter, Squasher, ValueChanger

Instance Method Summary collapse

Methods included from Transformable

#exclusive_merge, #exclusive_merge!, #map_to_hash, #squash, #squash!, #to_deep_hash, #to_deep_hash!

Methods included from Transposeable

#transpose, #transpose!

Methods included from Changeable

#change_values, #change_values!

Methods included from KeyChangeable

#append_to_keys, #chain_change_keys, #chain_change_keys!, #change_keys, #change_keys!, #prepend_to_keys, #remap_keys, #remap_keys!, #sort_keys, #sort_keys!

Methods included from Cameliazable

#camelize_keys, #camelize_keys!, #lower_camelize_keys, #lower_camelize_keys!, #underscore_keys, #underscore_keys!

Instance Method Details

#chain_fetch(*keys, &block) {|key_not_found, keys_missing| ... } ⇒ ::Object

Crawls through the hash fetching a key value from inside it

this is the equivalent of chaining several calls to fetch method

“‘

hash.chain_fetch(:key1, :key2)
hash.fetch(:key1).fetch(:key2)

“‘

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]

Parameters:

  • keys (::Array<::Object>)

    List of keys to be fetched

  • block (::Proc)

    block to be called in case of key not found

Yields:

  • (key_not_found, keys_missing)

    The result of the yield will be the returned value instead of raising KeyError

Returns:



58
59
60
# File 'lib/darthjee/core_ext/hash.rb', line 58

def chain_fetch(*keys, &block)
  ::Hash::ChainFetcher.new(self, *keys, &block).fetch
end