如何从混合模块中调用`self.class`?

How to call `self.class` from a mix-in module?

我有一个模块要包含在其他 类 中。它使用 Object#class 方法,如下所示: (sorbet.run link)

# typed: true
module M
  def foo
    self.class
  end
end

对此,冰糕说

editor.rb:4: Method class does not exist on M https://srb.help/7003
     4 |    self.class
            ^^^^^^^^^^
  Did you mean to `include Object` in this module?
    ???: Did you mean: Object#class?

现在变得有趣了。 Error reference for 7003 does describe that this guards against type errors in modules to be included in BasicObject. Fine, so I include Object, as the checker tells me: (sorbet.run link)

# typed: true
module M
  include Object
  def foo
    self.class
  end
end

错误信息非常无用,链接的 page #5032 不存在。

editor.rb:2: Only modules can be included. This module or class includes Object https://srb.help/5032
     2 |module M
        ^^^^^^^^

我花了一段时间才意识到它试图告诉我不能包含 Class,它是 Module 的子类。对比Ruby的错误信息:

$ ruby -e 'module M; include Object; end'
Traceback (most recent call last):
        2: from -e:1:in `<main>'
        1: from -e:1:in `<module:M>'
-e:1:in `include': wrong argument type Class (expected Module) (TypeError)

如何让我的代码通过这里的 typed: true 级别?

我目前的解决方法是:(sorbet.run link)

# typed: true
module ObjectInterface
  def class; super; end
end
module M
  include ObjectInterface
  def foo
    self.class
  end
end

这实际上是两个错误!感谢您指出他们:

classKernel 上不在我们的垫片中:https://github.com/sorbet/sorbet/pull/1050 我们永远不应该建议包含不是 Module 的内容:https://github.com/sorbet/sorbet/pull/1047