Ruby中的循环依赖 [英] Circular Dependencies in Ruby

查看:81
本文介绍了Ruby中的循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有两个类Foo和Foo Sub,它们分别在不同的文件foo.rb和foo_sub.rb中.

Let's say we have two classes, Foo and Foo Sub, each in a different file, foo.rb and foo_sub.rb respectively.

foo.rb:

require "foo_sub"
class Foo
    def foo
        FooSub.SOME_CONSTANT
    end
end

foo_sub.rb:

foo_sub.rb:

require "foo"
class FooSub < Foo
    SOME_CONSTANT = 1
end

由于循环依赖关系,这将无法正常工作-我们不能在没有另一个类的情况下定义任何一个.我见过各种解决方案.我要避免其中两个-即将它们放在同一文件中并删除循环依赖项.因此,我找到的唯一其他解决方案是前向声明:

This isn't going to work due to the circular dependency - we can't define either class without the other. There are various solutions that I've seen. Two of them I want to avoid - namely, putting them in the same file and removing the circular dependency. So, the only other solution I've found is a forward declaration:

foo.rb:

class Foo
end
require "foo_sub"
class Foo
    def foo
        FooSub.SOME_CONSTANT
    end
end

foo_sub.rb

foo_sub.rb

require "foo"
class FooSub < Foo
    SOME_CONSTANT = 1
end

不幸的是,如果我有三个文件,我将无法正常工作:

Unfortunately, I can't get the same thing to work if I have three files:

foo.rb:

class Foo
end
require "foo_sub_sub"
class Foo
    def foo
        FooSubSub.SOME_CONSTANT
    end
end

foo_sub.rb:

foo_sub.rb:

require "foo"
class FooSub < Foo
end

foo_sub_sub.rb:

foo_sub_sub.rb:

require "foo_sub"
class FooSubSub < FooSub
    SOME_CONSTANT = 1
end

如果我需要foo_sub.rb,则FooSub是foo_sub_sub.rb中的未初始化常量.有什么想法可以解决这个问题,而不将它们放在同一文件中或删除循环依赖吗?

If I require foo_sub.rb, then FooSub is an uninitialized constant in foo_sub_sub.rb. Any ideas how to get around this without putting them in the same file nor removing the circular dependency?

推荐答案

如果您需要从超类访问子类,则很有可能模型被破坏了(即它应该是一个类).

If you need to access a subclass from a superclass then there's a good chance that your model is broken (i.e. it should be one class).

也就是说,有两个显而易见的解决方案:

That said, there are a couple of obvious solutions:

1)仅创建一个需要foo文件的文件:

1) just create a file that requires the foo files:

all_foos.rb:

all_foos.rb:

require "foo.rb"
require "foo_sub.rb"

并从foo.rb和foo_sub.rb中删除需求.

and remove the requires from foo.rb and foo_sub.rb.

2)从foo.rb中删除require

2) remove the require from foo.rb

3)从foo_sub.rb中删除require,并将require放在类定义之后的foo.rb中.

3) remove the require from foo_sub.rb and put the require in foo.rb after the class definition.

Ruby不是C ++,在您调用Foo#foo();)之前,它不会抱怨FooSub.SOME_CONSTANT

Ruby isn't C++, it won't complain about FooSub.SOME_CONSTANT until you call Foo#foo() ;)

这篇关于Ruby中的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆