S
S
Shaks2017-12-16 16:54:53
ruby
Shaks, 2017-12-16 16:54:53

How to call a static method on a class module?

noob 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 code above, we have a class BarClassthat includes a module FooModule
. Accordingly, the class has a static method foo_method
. Why can't I 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 `<main>'
2.4.1 :003 >

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kozlov, 2017-12-16
@shaks

include - adds module methods to an object.
extend - calls include on the object's singleton class.
Correct option:

module FooModule
  def foo_method
    puts 'TestModule'
  end
end

class BarClass
  extend FooModule
end

More

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question