Class: Dry::Container::Resolver

Inherits:
Object
  • Object
show all
Defined in:
lib/dry/container/resolver.rb

Overview

Default resolver for resolving items from container

Instance Method Summary collapse

Instance Method Details

#call(container, key) {|key| ... } ⇒ Mixed

Resolve an item from the container

Parameters:

  • container (Concurrent::Hash)

    The container

  • key (Mixed)

    The key for the item you wish to resolve

Yields:

  • Fallback block to call when a key is missing. Its result will be returned

Yield Parameters:

  • key (Mixed)

    Missing key

Returns:

  • (Mixed)

Raises:

  • (KeyError)

    If the given key is not registered with the container (and no block provided)



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/dry/container/resolver.rb', line 26

def call(container, key)
  item = container.fetch(key.to_s) do
    if block_given?
      return yield(key)
    else
      raise KeyError.new(%(key not found: "#{key}"), key: key.to_s, receiver: container)
    end
  end

  item.call
end

#each(container, &block) ⇒ Object

Note:

In discussions with other developers, it was felt that being able to iterate over not just the registered keys, but to see what was registered would be very helpful. This is a step toward doing that.

Calls block once for each key in container, passing the key and the registered item parameters.

If no block is given, an enumerator is returned instead.

Returns:

  • Key, Value



83
84
85
# File 'lib/dry/container/resolver.rb', line 83

def each(container, &block)
  container.map { |key, value| [key, value.call] }.each(&block)
end

#each_key(container, &block) ⇒ Object

Calls block once for each key in container, passing the key as a parameter.

If no block is given, an enumerator is returned instead.

Returns:

  • Hash



68
69
70
# File 'lib/dry/container/resolver.rb', line 68

def each_key(container, &block)
  container.each_key(&block)
end

#key?(container, key) ⇒ Bool

Check whether an items is registered under the given key

Parameters:

  • container (Concurrent::Hash)

    The container

  • key (Mixed)

    The key you wish to check for registration with

Returns:

  • (Bool)


48
49
50
# File 'lib/dry/container/resolver.rb', line 48

def key?(container, key)
  container.key?(key.to_s)
end

#keys(container) ⇒ Array

An array of registered names for the container

Returns:

  • (Array)


57
58
59
# File 'lib/dry/container/resolver.rb', line 57

def keys(container)
  container.keys
end