首页 > 解决方案 > 如何在 rake 任务上运行 sorbet typecheck

问题描述

我注意到默认情况下,srb initetc 不会在 rake 任务上放置 # typed 标志。但是,在 VSCode 上,它确实在 rake 任务上显示错误(例如缺少常量)。

我尝试添加# typed: true到 rake 任务,但它会立即显示错误,例如“命名空间在 Root 中不可用”。有没有人尝试过检查您的 rake 任务?这样做的设置是什么?

标签: ruby-on-railsrakesorbet

解决方案


Rake monkeypatches 全局main对象(即顶级代码)以扩展其 DSL:

# Extend the main object with the DSL commands. This allows top-level
# calls to task, etc. to work from a Rakefile without polluting the
# object inheritance tree.
self.extend Rake::DSL

lib/rake/dsl_definition.rb

Sorbet 无法模拟对象的单个实例(在本例中main)与该实例的类(在本例中)具有不同的继承层次结构Object

为了解决这个问题,我们建议重构Rakefile一个继承层次结构明确的新类:

# -- my_rake_tasks.rb --

# (1) Make a proper class inside a file with a *.rb extension
class MyRakeTasks
  # (2) Explicitly extend Rake::DSL in this class
  extend Rake::DSL

  # (3) Define tasks like normal:
  task :test do
    puts 'Testing...'
  end

  # ... more tasks ...
end

# -- Rakefile --

# (4) Require that file from the Rakefile
require_relative './my_rake_tasks'

或者,我们可以编写一个 RBIObject使其看起来像extend Rake::DSL. 这个 RBI大部分是错误的:并非所有实例Object都有 this extend,只有一个实例有。我们建议这种方法,因为它可能使它看起来像一些代码类型检查,即使方法喜欢tasknamespace未定义。如果你想这样做,你可以写这个 RBI 文件Object

# -- object.rbi --

# Warning!! Monkeypatches all Object's everywhere!
class Object
  extend Rake::DSL
end

推荐阅读