在下面的代码中,我想调用包含 self.hello
内部模块的类的类方法 done
说明:
A::bonjour
将调用 Mod::hello
,B::ciao
也会调用 B::ciao
我希望能够检测 Mod::hello
中的“调用类”(A 或 B),以便能够调用 A::done
或 B::done
module Mod
def self.hello
puts "saying hello..."
end
end
class A
include Mod
def self.bonjour
Mod::hello
end
def self.done
puts "fini"
end
end
class B
include Mod
def self.ciao
Mod::hello
end
def self.done
puts "finitto"
end
end
最佳答案
虽然(也许)不像 Niklas 的答案那么干净,但它仍然很容易实现,并且 IMO 比 OP 中显示的使用模式更干净,OP 依赖于知道混合了哪个模块。
(当存在其他方法时,我不想像这样向 mixin 方法传递参数。)
输出:
pry(main)> A::bonjour
saying hello...
fini
pry(main)> B::ciao
saying hello...
finitto
胆量:
module Mod
module ClassMethods
def hello
puts "saying hello..."
done
end
end
def self.included(clazz)
clazz.extend ClassMethods
end
end
修改后的类声明,删除显式模块引用:
class A
include Mod
def self.bonjour
hello
end
def self.done
puts "fini"
end
end
class B
include Mod
def self.ciao
hello
end
def self.done
puts "finitto"
end
end
您还可以提供 done
的默认实现:
module Mod
module ModMethods
def hello
puts "saying hello..."
done
end
def done
throw "Missing implementation of 'done'"
end
end
def self.included(clazz)
clazz.extend ModMethods
end
end
正如本文的评论所指出的,如果OP中的代码片段忠实地代表了实际用例,您不妨使用extend
(而不是include
) >),让一切变得干净:
module Mod
def hello
puts "saying hello..."
done
end
def done
raise NotImplementError("Missing implementation of 'done'")
end
end
以及使用extend
的类:
class A
extend Mod
def self.bonjour
hello
end
def self.done
puts "fini"
end
end
关于ruby - 从 Ruby 中该类包含的模块调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8761145/