Extend/ include class methods

Hello everyone,

Let’s say I have some class and I want it to use instance methods as well as class methods from some module(s).

This code works just fine:

module Foo
  def bar
    1
  end
end

module Foo_
  def baz
    2
  end
end

class SomeClass
  include Foo
  extend Foo_
end

SomeClass.new.bar
SomeClass.baz

But Foo and Foo_ stand for the same kind of “topic”; what I mean is, let’s say SomeClass wouldn’t use modules and instead would be a subclass of some FooClass, then Foo_#baz would have been done as a class method FooClass.baz. So there is (regarding what Foo and Foo_ represent) some justified motivation to have just one module instead of two.

I was splitting it up into Foo and Foo_ only because it didn’t work when I initially tried it like this:

module Foo
  def self.baz
    1
  end

  def bar
    1
  end
end

class SomeClass
  include Foo
end

SomeClass.new.bar
SomeClass.baz
# Error: undefined method 'baz' for SomeClass.class

Do I have to stick with Foo and Foo_ or am I missing something/ doing something fundamentally wrong? If relevant: SomeClass (and other to become Foo-ish classes) will be based on total different types and not share any other characteristics than what makes them Foo/ comes from Foo.

If there is no other way, it’s no big deal. I just want to make sure I don’t go with separate modules for no reason.

Thanks!

You could use the included hook for this:

module Foo
  macro included
    def self.baz
      1
    end
  end
 
  def bar
    1
  end
end
 
class SomeClass
  include Foo
end
 
SomeClass.new.bar
SomeClass.baz
3 Likes

I’m glad I asked. That’s just perfect. Thanks!