Does dependency injection exist in Rails?

前端 未结 5 956
挽巷
挽巷 2020-12-24 10:24

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?

相关标签:
5条回答
  • 2020-12-24 11:04

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

    0 讨论(0)
  • 2020-12-24 11:04

    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 ).

    0 讨论(0)
  • 2020-12-24 11:10

    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.

    0 讨论(0)
  • 2020-12-24 11:11

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

    Whether there are DI frameworks for Ruby - check this question

    0 讨论(0)
  • 2020-12-24 11:14

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

    0 讨论(0)
提交回复
热议问题