title: Merge two Ruby modules but not include
body: <p>I want to merge two Ruby modules without breaking the lookup chain. Basically I want the behavior of <code>BothAnB</code> to be exactly as if I concatenated the textual source code from A and B and the new foo replaces the old. The problem occurs when MRO linearizes an inheritance diamond.</p>
  
  <pre><code>module O
    def foo; puts "O" end
  end
  
  module A
    include O
    def foo; puts "A"; super end
    def aaa; puts "aaa" end
  end
  
  module B
    include O
    def foo; puts "B"; super end
    def bbb; puts "bbb" end
  end
  
  module BothAnB
    #insert magic here such that a class C that includes BothAnB:
    # C.new.foo =&gt; B O
    # C.new.aaa =&gt; aaa
    # C.new.bbb =&gt; bbb
  end
  
  module JustA
    #insert magic here such that a class C that includes JustA:
    # C.new.foo =&gt; A O
    # C.new.aaa =&gt; aaa
    # C.new.bbb =&gt; FAIL
  end
  #and similarly JustB
  </code></pre>
  
  <p>A and B are fairly complex modules that can have deep inheritance chains (this is for a meta-programming framework that allows programmers to do just that).</p>
  
  <p><code>Include B, A</code> doesn't work because instead of the lookup BothAnB->B->A->O, I need it to be BothAnB->B->O(and optionally ->A).
  I've gotten close by:</p>
  
  <ul>
  <li>deep cloning entire inheritance tree of A (to remove diamond)</li>
  <li><code>undef_method</code> on the A's clone to remove methods found in B</li>
  <li>making a new method for <code>Module</code> to reflect this behavior</li>
  </ul>
  
  <p>Is there a better solution than this? I would ideally want to keep at least some of the modules recognizable when calling <code>BothAnB.ancestors</code>.</p>
  
  <p>[Note: I completely changed the question after getting two answers based on Phrogz's feedback, so if they seem irrelevant they are]</p>