You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决提取继承特定类的类方法时的Ruby Sorbet类型错误?

Sorbet无法识别模块中父类方法引用的解决方案

方案1:声明模块依赖的父类

通过T::Helpers.requires_ancestor明确告知Sorbet,该模块只能被继承自ApplicationController的类包含,这样静态检查就能识别base_method的存在:

# typed: true
extend T::Sig

class ApplicationController
  def base_method
  end
end

module Helper
  extend T::Helpers
  requires_ancestor { ApplicationController }

  def helper_method
    base_method
  end
end

class FooController < ApplicationController
  include Helper
end

class BarController < ApplicationController
  include Helper
end

FooController.new.helper_method
BarController.new.helper_method

方案2:显式断言self类型

如果不想限制模块的使用范围,可通过T.must结合类型断言,让Sorbet确认当前self是ApplicationController的子类实例:

# typed: true
extend T::Sig

class ApplicationController
  def base_method
  end
end

module Helper
  def helper_method
    T.must(self).base_method
  end
end

class FooController < ApplicationController
  include Helper
end

class BarController < ApplicationController
  include Helper
end

FooController.new.helper_method
BarController.new.helper_method

方案3:定义抽象方法签名

给ApplicationController的base_method添加签名,让模块依赖这个明确的接口,提升代码严谨性的同时解决检查错误:

# typed: true
extend T::Sig

class ApplicationController
  sig { void }
  def base_method
  end
end

module Helper
  sig { void }
  def helper_method
    base_method
  end
end

class FooController < ApplicationController
  include Helper
end

class BarController < ApplicationController
  include Helper
end

FooController.new.helper_method
BarController.new.helper_method

内容的提问来源于stack exchange,提问作者pvcresin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 19:50:00