4

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?

2
  • I get NameError: uninitialized constant Foo::Bar::ActivityCreator - is there a class definition missing from your example code? Commented Jul 21, 2015 at 17:28
  • ActivityCreator was an error - try extend Foo instead. Commented Jul 21, 2015 at 17:30

1 Answer 1

3

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.