[英]Ruby/Rails Dependency Injection
I am trying to learn about dependency injection in Ruby/Rails. 我试图了解Ruby / Rails中的依赖注入。 How can I remove
Builder
s explicit reference to Saw
using dependency injection? 如何使用依赖注入删除
Builder
对Saw
的显式引用?
class Builder
attr_reader :saw
def saw
@saw ||= Saw.new(4)
end
def cut_wood
Saw.saw
end
end
class Saw
attr_reader :blades
def initialize(blades)
@blades = blades
end
def saw
# do something
end
end
Move initialization of Saw
to the default argument. 将
Saw
初始化移动到默认参数。
class Builder
def saw(saw = Saw.new(4))
@saw = saw
end
def cut_wood
Saw.saw
end
end
Builder#saw
supports dependency injection now. Builder#saw
现在支持依赖注入。
Remember to remove attr_reader :saw
from your code because it's being overridden by your custom reader. 请记住删除
attr_reader :saw
从您的代码中查看,因为它被您的自定义阅读器覆盖。
class Builder
def initialize(saw=Saw.new(4))
@saw = saw
end
def cut_wood
@saw.saw
end
end
# Use it
b = Builder.new
b.saw
another_saw = AnotherSaw.new
b = Builder.new(another_saw)
b.saw
You initialize the Builder instance by a default saw. 您可以通过默认锯初始化Builder实例。 So you can either use the default one or use your own.
因此,您可以使用默认值,也可以使用自己的默认值。 This way you decoupled Saw from Builder.
这样你就可以将Saw与Builder分离。
By the way, I don't know hammer
is for so I didn't write it. 顺便说一句,我不知道
hammer
是为了所以我没有写它。 It looks nothing more than an attr reader in your code. 它看起来只不过是代码中的attr阅读器。
Also I don't need the necessity of attr_read :saw
so I removed it. 此外,我不需要
attr_read :saw
的必要性attr_read :saw
所以我删除它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.