繁体   English   中英

用Sorbet在Ruby中定义super class中定义的passthrough方法的方法签名

[英]Define method signature for passthrough method defined in super class in Ruby with Sorbet

我们正在考虑采用Sorbet ,我想知道是否可以定义以下方法的签名。 这是我们使用的常见模式:有一个抽象Service class,它有一个call class 方法,它负责初始化 class 并调用它的call实例方法。

# typed: true

class Service
  extend T::Sig
  extend T::Helpers

  abstract!

  def self.call(...)
    new(...).call
  end

  sig{abstract.void}
  def call
  end
end

class ServiceA < Service
  extend T::Sig
  extend T::Helpers

  sig{params(a: String).void}
  def initialize(a:)
    @a = a
  end

  sig{override.void}
  def call
    puts @a
  end
end

ServiceA.call(a: 'some value')

基本上, self.call的参数必须与子类初始化器的参数相匹配,并且它的返回值必须与子类的call实例方法的返回值相匹配。 有没有办法用冰糕做到这一点?

这是我得到的错误。

editor.rb:10: Splats are only supported where the size of the array is known statically https://srb.help/7019

正如 sorbet 文档已经指出的那样,splats 并没有得到 Sorbet 的很好支持。 但是,如果您对服务仅接受位置 arguments 的约束感到满意,您仍然可以对基本服务进行类型检查。您可以按照以下示例进行操作:

# typed: true

class Service
  extend T::Sig
  extend T::Helpers

  abstract!

  def self.call(**kwargs)
    new(**kwargs).call
  end
  
  def initialize(**kwargs); end

  sig { abstract.void }
  def call; end
end

class ServiceA < Service
  extend T::Sig
  extend T::Helpers

  sig { override.params(a: String).void }
  def initialize(a:)
    @a = a
  end

  sig{ override.void }
  def call
    puts @a
  end
end

ServiceA.call(a: 'some value')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM