Method: Injector#inject

Defined in:
lib/injector.rb

#inject(overrides = {}, &block) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/injector.rb', line 43

def inject(overrides = {}, &block)
  params = []
  keys = {}
  block.parameters.each_with_index do |(type, value), index|
    raise(
      ArgumentError,
      [
        "splash operator arguments are not permitted when injecting.",
        ":#{value} in #{ block.source_location }"
      ].join(" ")
    ) if type == :rest or type == :keyrest

    # fetch by index first! e.g. inject(0 => 40) { |x| x + 2 }
    result = overrides.fetch(index) do
      # then fetch by value
      overrides.fetch(value) do
        # Unfortunately, optional arguments are not possible, as
        # a Ruby block passed to `inject` will have exclusively optional arguments.
        # Instead, key arguments introduced in Ruby 2.0 should be used.
        if type == :key
          begin self.get(value)
          rescue RuleNotFound
          end
        else
          self.get(value)
        end
      end
    end
    if type == :key
      keys[value] = result
    else
      params << result
    end
  end

  if keys.empty?
    block.call(*params)
  else
    block.call(*params, keys)
  end
end