Reputation:
I have the following code - (from rubymonks)
module Foo
class ClassMethods
def guitar
"gently weeps"
end
end
end
class Bar
include Foo
def self.guitar
puts "hehe"
#call guitar function from ClassMethods
end
end
puts Bar.guitar
Here, how do I call the guitar function from ClassMethods. ClassMethods is not a super class, so can't use super keyword.
Upvotes: 0
Views: 53
Reputation: 114188
That kind of structure is usually used to both, include and extend a Module with a single call to include
. It works by setting up an included
callback that invokes the extend
call:
module Foo
def self.included(mod)
mod.extend(ClassMethods)
end
module ClassMethods
def guitar
"gently weeps"
end
end
end
class Bar
include Foo
def self.guitar
puts "hehe"
super
end
end
puts Bar.guitar
#=> hehe
#=> gently weeps
The above is equivalent to:
module Foo
module ClassMethods
def guitar
"gently weeps"
end
end
end
class Bar
include Foo
extend Foo::ClassMethods
def self.guitar
puts "hehe"
super
end
end
Of course, include Foo
only makes sense if there are instance methods (or constants / module variables). In your example, you only need extend
.
Upvotes: 1