Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend class in same module with class methods defined in module

Tags:

ruby

I have a module with some class methods I'd like to make available to classes within the module. However, what I'm doing is not working.

module Foo
  class << self
    def test
      # this method should be available to subclasses of module Foo
      # this method should be able to reference subclass constants and methods
      p 'test'
    end
  end
end

class Foo::Bar
  extend Foo
end

This fails:

Foo::Bar.test
NoMethodError: undefined method `test'

What am I doing wrong?

like image 760
doremi Avatar asked Oct 29 '25 15:10

doremi


1 Answers

When you extend a module from a class, the module's instance methods become class methods in the class. So you need:

module Foo
  def test
    puts "hi"
  end
end

class Foo::Bar
  extend Foo
end

Foo::Bar.test #=> hi

If you'd also like to have a module method Foo::test, which can be called from anywhere with Foo.test, change the above to:

module Foo
  def test
    puts "hi"
  end
  extend self
end

Foo::Bar.test #=> hi
Foo.test      #=> "hi"
like image 124
Cary Swoveland Avatar answered Nov 01 '25 14:11

Cary Swoveland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!