我正在用一个方法编写一个模块foo,它bar在接收者的类上调用一个类方法.我当前的方法是使用self.class.bar,除非在实例类中定义类方法而不是"真实"类方法,否则它的工作正常:
module M
def foo
self.class.bar
end
end
obj = Object.new
class << obj
include M
def self.bar
42
end
end
obj.foo # => NoMethodError: undefined method `bar' for Object:Class
Run Code Online (Sandbox Code Playgroud)
这是有道理的,因为obj.class不返回单例类.我可以使用obj.singleton_class,一切都会顺利进行:
module M
def foo
self.singleton_class.bar
end
end
obj = Object.new
class << obj
include M
def self.bar
42
end
end
obj.foo # => 42
Run Code Online (Sandbox Code Playgroud)
只有在单例类上定义方法的原因与上述相同.更糟糕的是,它为每个接收器创建了一个新的单例类,我想避免这些类,因为这些可能是相当多的对象.所以相反,我想要一些方法来检索对象的单例类,当且仅当它已经被定义时,即类型的东西obj.has_singleton_class ? obj.singleton_class : obj.class.我找不到任何方法来执行此检查.