Hi,
I’ve written a little ruby application with roughly 20 methods in two
classes which I have kind of wrapped in one module as a common namespace to
hold everything together. I introduced optparse on the module level to
parse options which worked fine.
Why do you use Optparse in a module? This is intended to be used for
processes because those only have a list of strings as arguments. For
libraries you can define arbitrary types as arguments or pass on individual
state. There is usually no need for parsing lists of strings.
Then I decided to put the part related to parsing the options into a
couple of methods due to readability / code style guide conformance but
that’s not working anymore.
Here’s what the simplified working code comes down to:
module ModuleWorking
puts "This works"
class MyClass
def my_method
# lot’s of stuff omitted here
end
end
end
And here’s an example of what I’m trying to achieve but what’s not working:
module ModuleNotWorking
def another_method
puts "This does not work"
end
another_method
class MyClass
def my_method
# lot’s of stuff omitted here
end
end
end
#=> NameError: undefined local variable or method `another_method’ for
ModuleNotWorking:Module
Here is another way to make it work:
$ruby <<EXAMPLE
module ModuleNotWorking
extend self
def another_method
puts "This does not work"
end
another_method
class MyClass
def my_method
# lot’s of stuff omitted here
end
end
end
EXAMPLE
This does not work
Well, now the message is misleading. 
What this basically does it extends the module instance with itself making
all methods defined in the module available as instance methods of the
module itself. This is a more implicit variant of what Greg suggested.
As I’m still kind of a ruby newbie I’m probably missing a basic concept
(OO?) but can’t really get my head around what’s wrong here…any hints would
be most welcome!
No, you're not missing a basic concept - certainly not OO. This is
basically how modules work: they define instance methods that can be made
usable in two ways:
Classes including modules. Then all instances of these classes can use
methods defined in the module like they were defined as instance methods of
the class.
Use method Object#extend(module). This will make the instance's singleton
class include the module. Then the same mechanism applies as above and
methods defined in the module are available as instance methods of the
instance on which you invoked #extend.
You can try these things nicely in IRB. Helpful methods: Class#ancestors,
Object#singleton_class, Object#class.
Kind regards
robert
···
On Wed, Nov 4, 2015 at 10:25 AM, Michael Schwarze <michael@schwarze-web.de> wrote:
--
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can -
without end}
http://blog.rubybestpractices.com/