Does dependency injection exist in Rails?

Ruby on-RailsRubySpringDependency Injection

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.

Solution 2 - Ruby on-Rails

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

Whether there are DI frameworks for Ruby - check https://stackoverflow.com/questions/283466/ruby-dependency-injection-libraries">this question

Solution 3 - Ruby on-Rails

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

Solution 4 - Ruby on-Rails

I use this IoC https://github.com/alexeypetrushin/micon in my Web Framework, most of time it stays hidden and silently solves issues of dependencies and component initializtion that otherwise should be solved manually.

You can see it in action here http://ruby-lang.info (this site powered with Rad, my web framework https://github.com/alexeypetrushin/rad_core ).

Solution 5 - Ruby on-Rails

Dependency injection is usually unnecessary with Ruby. Jamis Buck blogged extensively about the reasons why. Well worth a read.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkwsView Question on Stackoverflow
Solution 1 - Ruby on-RailsAaron QianView Answer on Stackoverflow
Solution 2 - Ruby on-RailsBozhoView Answer on Stackoverflow
Solution 3 - Ruby on-RailsmarcggView Answer on Stackoverflow
Solution 4 - Ruby on-RailsAlex CraftView Answer on Stackoverflow
Solution 5 - Ruby on-RailsJohn TopleyView Answer on Stackoverflow