Circular Dependencies in Ruby

前端 未结 3 1596
执笔经年
执笔经年 2020-12-17 17:28

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
         


        
3条回答
  •  春和景丽
    2020-12-17 17:59

    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) just create a file that requires the foo files:

    all_foos.rb:

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

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

    2) remove the require from foo.rb

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

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

提交回复
热议问题