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
driver = Driver.new
passenger = Passenger.new
car = Car.new :driver => driver, :passenger => passenger
end
class Car
attr_inject :driver
attr_inject :passenger
def initialize(options)
inject_attributes options
end
end
Injector Example
For more inversion of control, an Injector can be used.
class Application
include Inject
injector = Injector.new
injector.map :driver, Driver.new
injector.map :passenger, Passenger.new
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
injector = Injector.new
injector.map :driver, Driver.new
injector.map :passenger, Passenger.new
injector.factory :logger do |target|
Logger.new(target)
end
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