Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does dependency injection exist in Rails?

Does the fact that Rails have an MVC approach mean that is has dependency injection?

Or is there a reason that we don't talk about dependency injection in Rails?

If Rails does have dependency injection, what does it consist of?

like image 600
kws Avatar asked Feb 03 '10 09:02

kws


People also ask

Is dependency injection really necessary?

The dependency injection technique enables you to improve this even further. It provides a way to separate the creation of an object from its usage. By doing that, you can replace a dependency without changing any code and it also reduces the boilerplate code in your business logic.

What is the difference between IOC and dependency injection?

Inversion of control means the program delegates control to someone else who will drive the flow IOC (Inversion of control) is a general parent term while DI (Dependency injection) is a subset of IOC. IOC is a concept where the flow of application is inverted.

Is dependency injection an overkill?

If you have a really small project with 12 classes, then a DI framework is almost certainly overkill. As a rule of thumb, the point where it becomes truly useful is when you find yourself repeatedly writing code that wires up object graphs with multiple dependencies and have to think about where to put that code.


1 Answers

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

def initialize(model_klass)   @model_klass = model_klass end 

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.

like image 95
Aaron Qian Avatar answered Sep 28 '22 04:09

Aaron Qian