I want to invoke method a
from method of module B
. How can I do it? I don't want to specify A::a
every time.
module A
def self.a
"a"
end
end
module B
extend A
def self.b
a
end
end
p B::b # => undefined local variable or method `a' for B:Module
When using extend
or include
, Ruby will only mixin the instance methods. Extend will mix them in as class methods, but it won't mix in the class methods. Therefore, an easy solution to your query:
module A
def a ## Change to instance
"a"
end
end
module B
extend A
def self.b
a
end
end
p B::b #=> "a"
p B.b #=> "a"
I found here a method to solve it but it doesn't look good to me:
module A
module ClassMethods
def a
puts "a"
end
end
extend ClassMethods
def self.included( other )
other.extend( ClassMethods )
end
end
module B
include A
def self.b
a
end
end
p B::b # => "a"
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