Extend a class in the same module using class methods defined in the module
I have a module with some class methods that I would like to make available to the classes in the module. However, what I am 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?
+3
source to share
1 answer
When you are a extend
module from a class, the methods of the module instance become the classes of the class in the class. Therefore you need:
module Foo
def test
puts "hi"
end
end
class Foo::Bar
extend Foo
end
Foo::Bar.test #=> hi
If you would also like to have a module method Foo::test
that can be called from anywhere using Foo.test
, change the above to:
module Foo
def test
puts "hi"
end
extend self
end
Foo::Bar.test #=> hi
Foo.test #=> "hi"
+3
source to share