title: Ruby: Circular dependency detected while using Threads
body: <p>When I run this code, in 9/10 cases Rails raises RuntimeError:
  Circular dependency detected while autoloading constant SearchEngine</p>
  
  <pre class="lang-ruby prettyprint-override"><code>def search
    ts_start = Time.now
    results = []
    threads = []
    @engines.each do |name|
      threads &lt;&lt; Thread.new do
        engine = "#{name.capitalize}Engine".constantize.new @params, @location
        results &lt;&lt; engine.search  
        Thread.exit if results.length == @engines.length || (Time.now - ts_start) &gt; @timeout
      end
    end
    threads.each { |t| t.abort_on_exception = false; t.join }
    unless results.length == 0 then
      # do some stuff...
    end
  end
  </code></pre>
  
  <p>However, when I create the new 'engine' instance BEFORE the new thread:</p>
  
  <pre class="lang-ruby prettyprint-override"><code>engine = "#{name.capitalize}Engine".constantize.new @params, @location    
  threads &lt;&lt; Thread.new do
    results &lt;&lt; engine.search  
  </code></pre>
  
  <p>then it runs fine in 9/10 cases. But it still isn't 100%.</p>
  
  <p>When i'm not using threads at all, it runs fine everytime.</p>
  
  <p>Any suggestions how to modify the code?</p>