title: ruby: how to require correctly (to avoid circular dependencies)
body: <p>today i was facing a strange problem:
  got a 'missing method' error on a module, but the method was there and the file where the module was defined was required. After some searching i found a circular dependency, where 2 files required each other, and now i assume ruby silently aborts circular requires.</p>
  
  <hr>
  
  <p>Edit Begin: Example</p>
  
  <p>File 'a.rb':</p>
  
  <pre><code>require './b.rb'
  
  module A
      def self.do_something
          puts 'doing..'
      end
  end
  </code></pre>
  
  <p>File 'b.rb':</p>
  
  <pre><code>require './a.rb'
  
  module B
      def self.calling
          ::A.do_something
      end
  end
  
  B.calling
  </code></pre>
  
  <p>Executing b.rb gives <code>b.rb:5:in 'calling': uninitialized constant A (NameError)</code>. The requires have to be there for both files as they are intended to be run on their own from command line (i ommitted that code to keep it short).
  So the B.calling has to be there. One possible solution is to wrap the requires in <code>if __FILE__ == $0</code>, but that does not seem the right way to go.</p>
  
  <p>Edit End</p>
  
  <hr>
  
  <p>to avoid these hard-to-find errors (wouldn't it be nicer if the require threw an exception, by the way?), are there some guidelines/rules on how to structure a project and where to require what? For example, if i have</p>
  
  <pre><code>module MainModule
    module SubModule
      module SubSubModule
      end
    end
  end
  </code></pre>
  
  <p>where should i require the submodules? all in the main, or only the sub in the main and the subsub in the sub?</p>
  
  <p>any help would be very nice.</p>
  
  <h2>Summary</h2>
  
  <p>An explanation why this happens is discussed in forforfs answer and comments.</p>
  
  <p>So far best practice (as pointed out or hinted to by lain) seems to be the following (please correct me if i'm wrong):</p>
  
  <ol>
  <li>put every module or class in the top namespace in a file named after the module/class. in my example this would be 1 file named 'main_module.rb.'
  if there are submodules or subclasses, create a directory named after the module/class (in my example a directory 'main_module', and put the files for the subclasses/submodules in there (in the example 1 file named 'sub_module.rb'). repeat this for every level of your namespace.</li>
  <li>require step-by-step (in the example, the <code>MainModule</code> would require the <code>SubModule</code>, and the <code>Submodule</code> would require the <code>SubSubModule</code>)</li>
  <li>separate 'running' code from 'defining' code. in the running code require once your top-level module/class, so because of 2. all your library functionality should now be available, and you can run any defined methods.</li>
  </ol>
  
  <p>thanks to everyone who answered/commented, it helped me a lot!</p>