title: What is a good practice for dependency injection in Ruby?
body: <p>I've been reading Sandi Metz's <em>Practical Object-Oriented Design in Ruby</em> and many sites online discussing design in Ruby. Something I've had a hard time fully understanding is the proper way to implement dependency injection.</p>
  
  <p>The internet is flooded with blog posts that explain how dependency injection works in what I think is a very partial way.</p>
  
  <p>I understand that this is supposed to be bad:</p>
  
  <pre><code>class ThisClass
    def initialize
      @another_class = AnotherClass.new
    end
  end
  </code></pre>
  
  <p>While this is a solution:</p>
  
  <pre><code>class ThisClass
    def initialize(another_class)
      @another_class = another_class
    end
  end
  </code></pre>
  
  <p>And that I could send the AnotherClass.new like this: </p>
  
  <pre><code>this_class = ThisClass.new(AnotherClass.new)
  </code></pre>
  
  <p>That is the approach that Sandi Metz recommends at least. What I don't understand is where should a line like that go? It has to go somewhere and generally in examples of this what's shown is a line like that being placed totally outside of any class, method, or module as if I'm simply entering it all by hand in IRB for testing purposes.</p>
  
  <p><a href="https://sporto.github.io/blog/2013/09/25/simple-dependency-injection/" rel="noreferrer">This post</a> (among others) suggests this different approach:</p>
  
  <pre><code>class ThisClass
    def another_class
      @another_class ||= AnotherClass.new
    end
  end
  </code></pre>
  
  <p><a href="http://weblog.jamisbuck.org/2008/11/9/legos-play-doh-and-programming" rel="noreferrer">Jamis Buck</a> would take a similar approach like this:</p>
  
  <pre><code>class AnotherClass
  end
  
  class ThisClass
    def another_class_factory(class_name = AnotherClass)
      class_name.new
    end
  end
  </code></pre>
  
  <p>However, these two examples both preserve AnotherClass's name inside ThisClass, which Sandi Metz says is one of the main things we're trying to avoid.</p>
  
  <p>So what is the best practice for doing this? Should I make a 'dependency' module filled with methods that are factories for objects of each class in my application?</p>