All Lessons / How to use Dependency Injection in Ruby

How to use Dependency Injection in Ruby

#326 ยท January 8, 2020

Your Teacher | Chris Oliver

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.

Discussion

Loading...
logo Created with Sketch.

Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

© 2020 GoRails, LLC. All rights reserved.