From: Paul Brannan Date: 2002-02-22T08:54:07+09:00 Subject: Re: recursive require On Fri, Feb 22, 2002 at 07:39:06AM +0900, Ron Jeffries wrote: > I'm having a really odd thing happen with two files that mutually > require each other, and I'm hoping for help. Having two files that mutually require each other is almost always a bug. I'm not sure you've convinced me that you have a good reason to do this. > I have a file of code and a corresponding file of tests. They have the > same main program, which is to run the tests (unless there's something > in the args, as usual). > > So I set up the code file to require the tests file and the tests file > to require the code file. I understand why the tests depend on the code, but why must the code depend on the tests? > It turns out that, if I start to run, say, the code, Ruby will > > begin code > code requires tests: > begin tests > tests requires code: > begin code > code requires tests: > tests load = false > end code > defining code classes **** > code load = true > end tests > defining test classes > tests load = true > end code > defining code classes **** I can reproduce this in a small test case. It appears that if I add the following to the top of both code.rb and tests.rb: $".push(__FILE__) then I get the following output: begin code code requires tests: begin tests tests requires code: code load = false defining test classes done defining test classes end tests tests load = true defining code classes done defining code classes end code Note that because the tests are defined first, they cannot use any constants defined in the code classes. > The above is an actual printout from the program, except that I manually > tabbed it to make it easier to read. I've written an "iputs" method and I manipulate $indent inside code.rb and tests.rb to get my indentation. Call me lazy. :) > Note that the code classes are defined twice. If I do it the other way > around, running the test file, then it happens the other way around: the > tests are loaded twice and the test files defined twice. > > Either way it's weird. Worst of all, the program runs differently > depending which file I load first. > > So ... any advice will be very welcome. What am I missing? I don't have any good advice, but I think the old (possibly overused) doctor patient joke applies here: Patient: "Hey Doc! It hurts when I drop this anvil on my foot!" Doctor: "So don't drop an anvil on your foot!" Hope this helps, Paul