module MinDI::Injectable

Include this in a container class to allow use of inject_into within services. See examples/inject.rb. Including this module also extends the class with the Container module, so a simple shortcut to making a fully functional injectable container is to simply include Injectable.

This module can be used outside of the context of MinDI::Container: almost any object can be injected into any other. For example:

x = [1,2,3]
y = {}
x.extend MinDI::Injectable
x.inject_into y
p y.reverse      => [3, 2, 1]

Note that injecting an Injectable object into another object never interferes with methods of the latter object.

Note that injected methods operate on the injecting instance, not the injectee. So instance variables…

Note similarity to Forwardable and Delegator in the stdlib. However, Injectable is more passive in that (as noted above) it only affects the handling of methods that are missing in the target object. In that respect, Injectable is a little like inheritance (except as noted above about which instance is operated on).

Public Instance Methods

inject_into(obj) click to toggle source

Inject the container’s services into obj. The service methods can be called from within the object’s methods, and they will return the same objects as if they were called from the container.

Returns obj, so that the method can be called within service definitions.

    # File lib/mindi.rb
309 def inject_into obj
310   begin
311     obj.extend Injected
312   rescue TypeError
313     warn "#{caller[2]}: warning: class #{obj.class} cannot be injected into"
314     return obj
315   end
316 
317   cont = obj.instance_variable_get(:@__injectable__object__)
318   if cont and cont != self
319     raise NonUniqueContainerError,
320       "Object #{obj.inspect} already belongs to #{cont.inspect}." +
321       " Was attempting to inject #{self.inspect} into it."
322   end
323   
324   obj.instance_variable_set(:@__injectable__object__, self)
325   obj
326 end