Dependency injection
in ruby
@huydx
what is
depedency injection
(DI)
dependency:
a part of your code "use"
another part
dependency injection:
how you inject a part of your
code in another part
Some examples
example
class Train
attr_accessor :food_service, :drink_service
def initialize(food_service, drink_service)
@food_service = food_service
@drink_service = drink_service
end
def serve(customer = Customer.new)
customer.eat(food_service.make_food)
customer.drink(drink_service.make_drink)
customer.sleep
end
end
example
class Train
attr_accessor :food_service, :drink_service
def initialize(food_service, drink_service)
@food_service = food_service
@drink_service = drink_service
end
def serve(customer = Customer.new)
customer.eat(food_service.make_food)
customer.drink(drink_service.make_drink)
customer.sleep
end
end
Train depends on
food service and
drink service
Train depends
on customer
You already use it
everyday!
Some "ruby" ways:
- constructor (initialize)
- parameter passing
- module include / extend
- inheritance
Disadvantages
- constructor (initialize)+
parameter passing:
api changes -> parameter
changes
Disadvantages
- module include / extend
poison method call space,
sometimes you don't know
what is included??!!
Disadvantages
- inheritance
create once, stick
forever!! Parent API/
interface needed to be
carefully design
Another DI approach (not ruby
way):
- Use DI framework
- define dependencies in configuration
file
- found https://github.com/
dsawardekar/encase
Point: is it really needed??
Point is: why do you
need to care about DI?
Some points:
- Testability
- Loosely coupled
- Code extensibility

DI in ruby