Circular Dependencies in Ruby

前端 未结 3 1599
执笔经年
执笔经年 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:41

    Another decent option is to use the autoload feature of Ruby.

    It works like this:

     module MyModule
          autoload :Class1, File.join(File.dirname(__FILE__), *%w[my_module class1.rb])
          autoload :Class2, File.join(File.dirname(__FILE__), *%w[my_module class2.rb])
          # Code for MyModule here
     end
    

    and is described well here:

    http://talklikeaduck.denhaven2.com/2009/04/06/all-that-you-might-require

提交回复
热议问题