Ruby-on-rails Rails 中是否存在依赖注入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2190812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:14:02  来源:igfitidea点击:

Does dependency injection exist in Rails?

ruby-on-railsrubyspringdependency-injection

提问by kws

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

Rails 具有 MVC 方法这一事实是否意味着具有依赖注入?

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

或者有什么原因我们不谈论 Rails 中的依赖注入?

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

如果 Rails 确实有依赖注入,它由什么组成?

采纳答案by John Topley

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

Ruby 通常不需要依赖注入。贾米斯·巴克 (Jamis Buck)发表了大量关于原因的博客。非常值得一读。

回答by Aaron Qian

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

IoC 是一把大锤,但 DI 每天都在 Ruby / Rails 中发生。无论何时:

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 Railtiesgem itself is mostly a DI Engine. You can injectyour favoriate ORM, various plugin configs, and generators.

这是DI。这个范式也用在 Rails 源代码的各个地方。例如,Railtiesgem 本身主要是一个 DI 引擎。你可以注入你喜欢的 ORM、各种插件配置和生成器。

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.

你使用什么语言并不重要,只要你需要在某处插入行为/代码,你可能正在使用它。

回答by Bozho

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

依赖注入是一种范式,所以它存在于每一种面向对象的语言中。

Whether there are DI frameworks for Ruby - check this question

是否有 Ruby 的 DI 框架 - 检查这个问题

回答by marcgg

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

我会说你不需要 ruby​​ 这样的东西......但如果你真的想要,有些人有解决方法

回答by Alexey Petrushin

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

我在我的 Web 框架中使用这个 IoC https://github.com/alexeypetrushin/micon,大部分时间它保持隐藏状态并默默地解决依赖和组件初始化的问题,否则应该手动解决。

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

您可以在http://ruby-lang.info(此站点由 Rad 提供支持,我的 Web 框架https://github.com/alexeypetrushin/rad_core)看到它的运行情况。