我正在实验添加冰糕类型的信息到我的宝石,pdf-阅读器。我不希望sorbet成为创业板的运行时依赖项,因此所有类型的注释都在rbi/目录中的外部文件中。我也不能在我的类中扩展T::Sig。
我希望在某些文件中启用typed: strict,但是这样做会标志着我使用了一些实例变量而没有类型注释:
./lib/pdf/reader/rectangle.rb:94: Use of undeclared variable @bottom_left https://srb.help/6002
94 | @bottom_left = PDF::Reader::Point.new(
^^^^^^^^^^^^
./lib/pdf/reader/rectangle.rb:98: Use of undeclared variable @bottom_right https://srb.help/6002
98 | @bottom_right = PDF::Reader::Point.new(
^^^^^^^^^^^^^
./lib/pdf/reader/rectangle.rb:102: Use of undeclared variable @top_left https://srb.help/6002
102 | @top_left = PDF::Reader::Point.new(
^^^^^^^^^
./lib/pdf/reader/rectangle.rb:106: Use of undeclared variable @top_right https://srb.help/6002
106 | @top_right = PDF::Reader::Point.new(建议的修复方法是使用T.let()
@top_right = T.let(PDF::Reader::Point.new(0,0), PDF::Reader::Point)但是,我不能这样做,因为它需要运行时依赖于sorbet。
是否可以在rbi文件中记录实例变量的注释?
发布于 2021-12-29 12:07:58
根据文献资料,“RBI文件的语法与普通的Ruby相同,只是方法定义不需要实现。”因此,在RBI文件中声明实例变量类型的语法与Ruby文件中的语法相同:
sig do
params(
x1: Numeric,
y1: Numeric,
x2: Numeric,
y2: Numeric
).void
end
def initialize(x1, y1, x2, y2)
@top_right = T.let(PDF::Reader::Point.new(0,0), PDF::Reader::Point)
# …
end另一种选择是使用RBS语法,而不是RBI语法,RBI语法支持实例变量的类型注释。然而,我发现在苏格兰皇家银行的支持方面,我发现了相互矛盾的信息。网上有人声称,Sorbet支持苏格兰皇家银行。索布特常见问题用未来时态谈论苏格兰皇家银行的支持。另一方面,FAQ谈论的“未来”是Ruby 3的发布,这实际上是过去的一年。
在苏格兰皇家银行,它应该是这样的:
module PDF
class Reader
@top_left: Numeric
@top_right: Numeric
@bottom_left: Numeric
@bottom_right: Numeric
class Rectangle
def initialize: (
x1: Numeric,
y1: Numeric,
x2: Numeric,
y2: Numeric
) -> void
end
end
end或者,因为它们也是attr_reader的,所以仅仅这样做就足够了。
module PDF
class Reader
attr_reader top_left: Numeric
attr_reader top_right: Numeric
attr_reader bottom_left: Numeric
attr_reader bottom_right: Numeric
class Rectangle
def initialize: (
x1: Numeric,
y1: Numeric,
x2: Numeric,
y2: Numeric
) -> void
end
end
end我相信,这也会隐式地键入相应的实例变量,但我还没有对此进行测试。
https://stackoverflow.com/questions/70515191
复制相似问题