Class: FunRuby::Container::Resolve

Inherits:
Object
  • Object
show all
Defined in:
lib/fun_ruby/container/resolve.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(aliases:, container:) ⇒ Resolve

Returns a new instance of Resolve.



22
23
24
25
# File 'lib/fun_ruby/container/resolve.rb', line 22

def initialize(aliases:, container:)
  @aliases = aliases
  @container = container
end

Class Method Details

.build(aliases: [], container: FunRuby.container) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/fun_ruby/container/resolve.rb', line 10

def self.build(aliases: [], container: FunRuby.container)
  formatted = aliases.each_with_object({}) do |key, namespace|
    if key.is_a?(::Hash)
      namespace.merge!(key.map { |k, v| [k, v].map(&:to_s) }.to_h)
    else
      namespace[key.to_s] = nil
    end
  end
  new(aliases: formatted.to_a.reverse.to_h, container: container)
end

Instance Method Details

#call(key) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/fun_ruby/container/resolve.rb', line 28

def call(key)
  key = key.to_s
  aliases.each do |(namespace, shortcut)|
    full_key = build_full_key(namespace, shortcut, key)
    begin
      return container.fetch(full_key)
    rescue KeyError
      next
    end
  end

  container.fetch(key) do
    raise KeyError, "key #{key.inspect} has not been registered"
  end
end