Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a module class method be called from a class nested in that module?

Is it possible to call a module's class method from a nested class method? For instance, if I had:

module A
  def self.foo
    'hello'
  end
end

module A
  class B
    def self.bar
      foo # Fails since A is not in B's ancestor chain
    end
  end
end

I know that I can call foo directly on A by using

def self.bar
  A.foo
end

But ideally I would like a way to have A be part of B's ancestor chain if possible. Any tips would be appreciated.

like image 397
Craig Kochis Avatar asked Dec 04 '25 17:12

Craig Kochis


1 Answers

I'm not aware of a straightforward way to do exactly what you're asking. But you can move A's self methods to instance methods in another module and have B extend that module:

module A
  module ClassMethods
    def foo
      'hello'
    end
  end
  extend ClassMethods
end

module A
  class B
    extend A::ClassMethods

    def self.bar
      foo
    end
  end
end
like image 119
Dave Schweisguth Avatar answered Dec 06 '25 07:12

Dave Schweisguth