Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby: Dynamically defining class methods in a module
    primarykey
    data
    text
    <p>I'm having trouble dynamically defining class methods within a module. See code below. I get a <code>NameError: undefined local variable or method</code> when trying to reference another class method in the module. Seems like this might be a scope or context issue, but I've not been able to figure it out so far.</p> <pre><code>module Bar def self.included(base) base.extend ClassMethods end module ClassMethods def fruits ["apple", "orange", "banana"] end def example_function(string) string.upcase end fruits.each do |fruit| method_name = fruit.to_sym define_method(method_name) { example_function(fruit) } end end end class Foo include Bar end puts Foo.apple puts Foo.orange puts Foo.banana </code></pre> <p>I want to be able to call:</p> <pre><code>puts Foo.apple =&gt; "APPLE" puts Foo.orange =&gt; "ORANGE" puts Foo.banana =&gt; "BANANA" </code></pre> <p>Currently when I try any of these I get the following error: <code>NameError: undefined local variable or method 'fruits' for Bar::ClassMethods:Module</code></p> <p>Additionally, class methods in Bar::ClassMethods should be available to Foo, so I should be able to call:</p> <pre><code>puts Foo.fruits =&gt; ["apple", "orange", "banana"] </code></pre> <p>Requirements:</p> <ol> <li>All code is within a single module.</li> <li>The module allows mixing both instance and class methods (article below).</li> <li>The target methods are dynamically defined.</li> </ol> <p><em>Read "Include vs Extend in Ruby" (esp. section titled "A Common Idiom") <a href="http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/" rel="nofollow">http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/</a></em></p> <p>Help with this is greatly appreciated!</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.
    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