How to Design Module Method?

Hi,

If I define a module method like this:

module MyMod
def MyMod.my_method
end
end

then I can invoke it like this:

irb> MyMod.my_method
=> nil

but I cannot invoke my_method without the module name, even if I include
the module:

irb> include MyMod
=> Object
irb> my_method
NameError: undefined local variable or method `my_method’ for
main:Object

Now, if I define the method like this:

module MyMod
def my_method
end
end

then I cannot invoke my_method even with the module name:

irb> MyMod.my_method
NoMethodError: undefined method `my_method’ for MyMod:Module

but I can invoke it if I include the module:

irb> include MyMod
=> Object
irb> my_method
=> nil

Therefore, my question is, is there any way so that both means of
invoking work, i.e., for people who don’t “include” the module they can
type “MyMod.my_method”, and for people who “include” the module they can
simply type “my_method”? (I am using Ruby 1.9.2.)

Regards,

Bill

Hi Robert,

To the best of my knowledge, in the methods I am not making use any
context/state. Thanks a lot for your reply.

(Based on my further search, it seems we can use “module_function”; but
this falls into the “dual use”.)

Regards,

Bill

On Thu, Nov 24, 2011 at 7:13 PM, Admin T.
[email protected] wrote:

main:Object
irb> MyMod.my_method
invoking work, i.e., for people who don’t “include” the module they can
type “MyMod.my_method”, and for people who “include” the module they can
simply type “my_method”? (I am using Ruby 1.9.2.)

There are various methods, this is one of them:

irb(main):001:0> module Foo
irb(main):002:1> def bar;123;end
irb(main):003:1> extend self
irb(main):004:1> end
=> Foo
irb(main):005:0> Foo.bar
=> 123
irb(main):006:0> class X
irb(main):007:1> include Foo
irb(main):008:1> def test;bar;end
irb(main):009:1> end
=> nil
irb(main):010:0> X.new.test
=> 123

BUT: both uses are quite different. When invoking on the module you
are basically using an algorithm which typically does not use context
(read: “state”). When invoking on the instance of a class which
includes the module then it can potentially use context (i.e. instance
state). Both uses are quite different which is why I generally
suggest to not do this and keep aspects separate and not do this “dual
use”.

Kind regards

robert