我正在嘗試將冰糕型別資訊添加到我的 gem pdf 閱讀器中。我不希望冰糕成為 gem 的運行時依賴項,因此所有型別注釋都位于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)
但是我不能這樣做,因為它需要運行時依賴于冰糕。
是否可以在 rbi 檔案中記錄實體變數的注釋?
uj5u.com熱心網友回復:
根據檔案“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 語法,后者本身支持實體變數的型別注釋。但是,我在 Sorbet 中發現了有關 RBS 支持的相互矛盾的資訊。網上聲稱 Sorbet 支持 RBS。OTOH,Sorbet 常見問題解答以未來時態談論 RBS 支持。在其他另一方面,“未來”對常見問題的會談是紅寶石3,這實際上是在過去一年釋放。
在 RBS 中,它看起來像這樣:
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_readers,所以可能就足夠了
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://www.uj5u.com/shujuku/400113.html
