How to use Dependency Injection in Ruby

January 8, 2020

Track your progress

Sign in to track your progress and access subscription-only lessons.

Log In

Your Teacher

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

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

Notes

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.

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.