简体   繁体   中英

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

We're considering adopting Sorbet and I wanted to know if it's possible to define the signature of the following method. This is a common pattern we use: there is an abstract Service class that has a call class method which is responsible for both initializing the class and calling the call instance method on it.

# 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')

Basically the params for self.call must match the params of the subclass's initializer and its return value must match the subclass's return value for the call instance method. Is there a way to do this with Sorbet?

Here is the error I get.

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

As the sorbet doc already states, splats are not very well supported by Sorbet. However, you can still type-check the base service if you're happy with the constraint that your services will only accept positional arguments. You can do so following this example:

# 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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