How to call a static method from a class module?

nubby question.. let's Say we have
# tmp.rb
module FooModule
 def self.foo_method
 puts 'TestModule'
end
end

class BarClass
 include FooModule
end


as you can see in the above code, we Have a class BarClass, which included the module FooModule
Accordingly, the class has a static method foo_method
Why am I unable to access it?
$ irb
2.4.1 :001 > require './tmp.rb'
 => true 
2.4.1 :002 > BarClass.foo_method
NoMethodError: undefined method `foo_method' for BarClass:Class
 from (irb):2
 from /home/shaks/.rvm/rubies/ruby-2.4.1/bin/irb:11:in `
' 2.4.1 :003 >
June 10th 19 at 14:36
1 answer
June 10th 19 at 14:38
Solution
include adds the methods of the module object.
extend — cause to include the singleton class of the object.

Correct option:
module FooModule
 def foo_method
 puts 'TestModule'
end
end

class BarClass
 extend FooModule
end


Read more
all right, thanks a lot!. Complement the answer is here still here the example again.

module FooModule

 def self.included(s)
s.extend(ClassMethods)
end

 module ClassMethods
 def foo_method1
 puts "called: #{__method__}"
end

 def foo_method2
 puts "called: #{__method__}"
end
end
end

class BarClass
 include FooModule
end


$ irb -r ./app.rb 
2.4.1 :001 > require './tmp.rb'
 => true 
2.4.1 :002 > BarClass.foo_method1
called: foo_method1
 => nil 
2.4.1 :003 > BarClass.foo_method2
called: foo_method2
 => nil 
2.4.1 :004 >
- Ulices commented on June 10th 19 at 14:41

Find more questions by tags Ruby