Dependency injection in ruby with example

Aydar Omurbekov
2 min readJul 5, 2021

Today we will talk about dependency injection.
We all know that tighly coupled code is bad and code smells.
So, dependency injection helps us avoid such problems.
Let me give you an example of the following code.

class Car
attr_reader :mileage

def initialize(mileage)
mileage = mileage
end
def worn_out
mileage * Tire.new(“Maxis”, 60, 34).radius
end
end
class Tire
attr_reader :brand, :radius, :width
def initialize(brand, radius, width)
brand = brand
width = width
radius = radius
end
end

As you see, we create a new instance of tire inside worn_out method.
If we change the name of Tire class or parameters number, we have to change the name of it inside that method too.
This is a tightly coupled code, classes depend on each other. If we change the class name or methods of Tire we also need to change the Car class.

Let’s solve this problem using dependency injection:

class Car
attr_reader :mileage, :tire
def initialize(mileage, tire)
mileage = mileage
tire = tire
end
def worn_out
mileage * tire.radius
end
end
class Tire
attr_reader :brand, :radius, :width
def initialize(brand, radius, width)
brand = brand
width = width
radius = radius
end
end

Car expects a ‘Duck’ that knows ‘radius’

Car.new(20000, Tire.new(“Maxis”, 60, 34))

In this example code, we injected the tire object into the constructor.
So Car class doesn’t depend on Tire class much.
If we change the Car class name or its parameters, it will not affect other classes.

Also, there is the Inversion of Control principle from SOLID created by Uncle Bob. According to this principle, code receives the flow of control from outside instead of being responsible to create it itself.

--

--