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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With