Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I invoke an instance method on a Ruby module without including it?
    primarykey
    data
    text
    <h3>Background:</h3> <p>I have a module which declares a number of instance methods</p> <pre><code>module UsefulThings def get_file; ... def delete_file; ... def format_text(x); ... end </code></pre> <p>And I want to call some of these methods from within a class. How you normally do this in ruby is like this:</p> <pre><code>class UsefulWorker include UsefulThings def do_work format_text("abc") ... end end </code></pre> <h3>Problem</h3> <p><code>include UsefulThings</code> brings in <em>all</em> of the methods from <code>UsefulThings</code>. In this case I only want <code>format_text</code> and explicitly do not want <code>get_file</code> and <code>delete_file</code>.</p> <p>I can see several possible solutions to this: </p> <ol> <li>Somehow invoke the method directly on the module without including it anywhere <ul> <li>I don't know how/if this can be done. (Hence this question)</li> </ul></li> <li>Somehow include <code>Usefulthings</code> and only bring in some of it's methods <ul> <li>I also don't know how/if this can be done</li> </ul></li> <li>Create a proxy class, include <code>UsefulThings</code> in that, then delegate <code>format_text</code> to that proxy instance <ul> <li>This would work, but anonymous proxy classes are a hack. Yuck.</li> </ul></li> <li>Split up the module into 2 or more smaller modules <ul> <li>This would also work, and is probably the best solution I can think of, but I'd prefer to avoid it as I'd end up with a proliferation of dozens and dozens of modules - managing this would be burdensome</li> </ul></li> </ol> <p>Why are there lots of unrelated functions in a single module? It's <code>ApplicationHelper</code> from a rails app, which our team has de-facto decided on as the dumping ground for anything not specific enough to belong anywhere else. Mostly standalone utility methods that get used everywhere. I could break it up into seperate helpers, but there'd be 30 of them, all with 1 method each... this seems unproductive</p>
    singulars
    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.
    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