attr_inject
attr_inject is an small and elegant dependency injection solution for Ruby.
Installation
gem install attr_inject
Usage
attr_inject can be used many ways scaling from the least inrtusive to more inrusive options.
Simple Example
Dependencies are injected via a Hash through the Object's constructor.
class Application
# initialize our dependencies
driver = Driver.new
passenger = Passenger.new
# inject our dependencies into our Car object
car = Car.new :driver => driver, :passenger => passenger
end
class Car
attr_inject :driver
attr_inject :passenger
def initialize()
inject_attributes
end
end
Injector Example
For more inversion of control, an Injector can be used.
class Application
include Inject
# Map our depedencies
injector = Injector.new
injector.map :driver, Driver.new
injector.map :passenger, Passenger.new
# Inject our dependencies into our car object
car = Car.new
injector.apply(car)
end
class Car
attr_inject :driver
attr_inject :passenger
end
Factory Example
Create an Injector to map objects and factories to.
require "attr_inject"
class Application
include Inject
# Map our depedencies
injector = Injector.new
injector.map :driver, Driver.new
injector.map :passenger, Passenger.new
# Factory dependencies are called
# on each inject and are passed it's
# target object
injector.factory :logger do |target|
Logger.new(target)
end
# Inject our dependencies into our car object
car = Car.new
injector.apply(car)
end
Our car object explicitly defines what dependencies it wants.
class Car
attr_inject :driver
attr_inject :passenger
attr_inject :logger
end