Note that there are some explanatory texts on larger screens.

plurals
  1. POadding class specific functionality in ruby modules
    primarykey
    data
    text
    <p>possibly I'm not explaining the concept very well, but I'm looking to add class methods to a series of ruby classes to enable them to hold class specific information which will then be called by individual instance methods of the classes.</p> <p>I can make it work, but it is a bit ugly. Can anyone as it requires 2 modules, one included and the other extended (see example code below).</p> <p>Can anyone think of a more elegant way of implementing this functionality ?</p> <p>Thanks</p> <p>Steve</p> <p>This module is extended to give class methods but adding an instance member to each class it is included in</p> <pre><code>module My1 def my_methods (*sym_array) @my_methods=sym_array end def method_list @my_methods end end </code></pre> <p>This module is included to give instance methods</p> <pre><code>module My2 def foo self.class.method_list.each { |m| self.send m } end end </code></pre> <p>Now use the modules - the ugliness is having to use an include and extend statement to allow me to pass a set of symbols to a class method which will then be implemented in an instance</p> <pre><code>class Foo extend My1 include My2 my_methods :baz def baz puts "Baz!" end end class Bar extend My1 include My2 my_methods :frodo def frodo puts "Frodo!" end end class Wibble &lt; Bar extend My1 include My2 my_methods :wobble def wobble puts "Wobble!" end end </code></pre> <p>Here is the required output - note that each class has its own instance @my_methods so the behaviour is different for the derived class Wibble &lt; Bar</p> <pre><code>f=Foo.new b=Bar.new w=Wibble.new f.foo #=&gt; "Bar!" b.foo #=&gt; "Frodo!" w.foo #=&gt; "Wobble!" </code></pre>
    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.
    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