Suppose I have a module:
module M
def self.foo
...
end
def bar
...
end
end
Module M
is included in a class.
class A
include M
end
I want to call foo
from bar
, which will eventually be called on an instance of A
. What's the best way to do this inside bar
?
Of course I can just say M.foo
, but that's duplication of the module's name, which feels unnecessary.
Usually, in a
module
, it's a good practice to have class-methods and instance-methods separate, like this:Now, in a class, I would ideally want to
include
this moduleM
in a way that I getA.foo
as class method andA.new.bar
as instance method. The trick for that isModule.included
.With this approach, you can refer the class method with
self.class
and it will automagically work.Hope it helps.