我有以下代码 - (来自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
在这里,我如何从ClassMethods调用吉他功能。 ClassMethods不是超类,因此不能使用super关键字。
答案 0 :(得分:1)
这种结构通常用于两者,包括和扩展模块,只需调用include
。它的工作原理是设置调用included
调用的extend
回调:
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
以上相当于:
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
当然,include Foo
只有在存在实例方法(或常量/模块变量)时才有意义。在您的示例中,您只需要extend
。