Does dependency injection exist in Rails? Does dependency injection exist in Rails? spring spring

Does dependency injection exist in Rails?


IoC is the big hammer, but DI happens everyday in Ruby / Rails. Whenever you do:

def initialize(model_klass)  @model_klass = model_klassend

This is DI. This paradigm is also used in various places in Rails source code. For example, the Railties gem itself is mostly a DI Engine. You can inject your favoriate ORM, various plugin configs, and generators.

Dependency Injection has a big and scary name, but what it boils down to is just decoupling class dependencies by ways of injecting the dependencies during runtime.

It doesn't matter what language you use, as long as you need to plug behavior / code in somewhere, you are probably using it.


Dependency Injection is a paradigm, so it exists in every object-oriented language.

Whether there are DI frameworks for Ruby - check this question


I'd say that you don't need such a thing with ruby... but if you really want to, some people have workarounds.