Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I "replace" a module included via ruby include function
    primarykey
    data
    text
    <p>As a follow up to <a href="https://stackoverflow.com/questions/2403057/how-can-i-reverse-rubys-include-function">How can I reverse ruby&#39;s include function</a>, which was well answered but turned out my simplification of the real problem mean't that the solution was not applicable.</p> <p>I'm now faced with this (names changed to protect identities!):</p> <pre><code>module OldFormHelpers def foo puts "foo" end def bar puts "bar" end end module Helpers include OldFormHelpers end </code></pre> <p>This gives me:</p> <pre><code>Helpers.instance_methods =&gt; ["bar", "foo"] Helpers.ancestors =&gt; [Helpers, OldFormHelpers] </code></pre> <p>This is code that I don't really have access to modify, without forking.</p> <p>What I want to do is create a new module;</p> <pre><code>module BetterFormHelpers def foo puts "better foo" end end </code></pre> <p>This needs to remove the behaviours from <code>OldFormHelpers</code>, and then add in the new stuff from <code>BetterFormHelpers</code></p> <p>The previous solution was to use <code>undef_method</code> like so:</p> <pre><code>Helpers.module_eval do OldFormHelpers.instance_methods do |m| undef_method(m) end end </code></pre> <p>However, after including <code>BetterFormHelpers</code>, Helpers.instance_methods doesn't contain "foo". The reason for this is explained at <a href="http://ruby-doc.org/core/classes/Module.src/M001652.html" rel="nofollow noreferrer">http://ruby-doc.org/core/classes/Module.src/M001652.html</a></p> <p>Using <code>remove_method</code> tells me that <code>Helpers</code> doesn't have the "foo" method, so I guess I need some way of removing the first inclusion from the ancestors chain...</p> <p>This was getting a bit long so I stopped putting so many snippets in towards the end, but I add an irb session showing the behaviour of undef/remove and then an include.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload