Skip to main content
Design Patterns:

How to use Dependency Injection in Ruby

Episode 326 · January 8, 2020

Dependency Injection is a common technique for making your code more flexible and testable by removing strict dependencies upon other classes, modules, and other types of dependencies in your code

Design Patterns

Dependency Injection is an approach you can use to design your code in a way that makes it more flexible.

If you have a method that depends upon another class or module, you have a strict dependency on that class or module. This makes it impossible to replace that class or module with another one if you needed to for some reason. Plus, you have to explicitly stub out the methods on the class or module for testing.

With Dependency Injection, you can extract the dependency to become an argument to your method. This allows anyone to override the dependency with their own. They might want to do this to implement a different backend.

For example, you might have the default export format as CSV, but someone wants a one-off export to Excel, or yaml, or json. By using dependency injection, none of the original code needs to change. The caller simply passes in a new dependency to be used instead.

This also has huge benefits when it comes to testing. You can use a custom test class to fake a dependency or you can use Mocks which we will talk about more in the next episode.


Earn a free month


Subscribe to the newsletter

Join 31,152+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.