Including singleton methods with a module?

Hi all!

I have a module, which defines several instance methods, and a singleton
(class) method also, which gets use one of the class methods of the
class which includes it.

I.e.:

···

module Mod
def self.s1
do_something_with(helperfn)
end

def fn1
	...
end

def fn2
	...
end

end

class C
include Mod

def self.helperfn
	...
end

end

Using like this, I cannot call C.s1(). I suppose I could take out s1
something like this, am I right?

module Mod2
def s1
do_something_with(helperfn)
end
[…]
end

class C
include Mod
extend Mod2
end

… Or maybe:

[…]
class C
include Mod
def self.s1() Mod.s1() end
end

But, I would like to use my module in my classes as simply is “include
Mod”. How can I do this?

Thanks,
Ferenc

Using like this, I cannot call C.s1(). I suppose I could take out s1
something like this, am I right?

you can use ::append_features

svg% cat b.rb
#!/usr/bin/ruby
module Mod
   module Intern
      def s1
         p "s1"
      end
   end
   
   def fn1
      p "fn1"
   end

   def self.append_features(mod)
      super
      mod.extend Intern
   end
end

class A
   include Mod
end

A.new.fn1
A.s1
svg%

svg% b.rb
"fn1"
"s1"
svg%

Guy Decoux

Thanks, the good old append_features worked. :slight_smile:

Ferenc

ts wrote:

···

Using like this, I cannot call C.s1(). I suppose I could take out s1
something like this, am I right?

you can use ::append_features