Home > Net >  Sorbet overrides URI from Kernel
Sorbet overrides URI from Kernel

Time:03-04

I have method as below

  sig do
    params(uri: URI).returns(String)
  end
  def get(uri)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.start
    response = http.request_get(uri.path)
    response.body
  ensure
    http&.finish
  end

Test method is like below (does not use sorbet)

def test_get_retry
    uri = URI('http://localhost:4567')
    instance = BookStoreHttpClient.new
    begin
      instance.get_with_retry(uri)
    rescue StandardError
      assert(true)
    end
end

But Sorbet complains with "Method host does not exist on URI", but it is a Kernel class actually.

Is there a way to tell Sorbet to use Kernel::URI instead of URI in sorbet/rbi/hidden-definitions/hidden.rbi

CodePudding user response:

Sorbet is correct, and the problem is not that it's using the wrong URI.

URI is not a type, it's a module that contains types: URI::Generic, URI::HTTPS etc. Kernel::URI is also not a type, it's a function that returns an instance of one of the types contained in the URI module.

For example:

URI("google.com") # => #<URI::Generic google.com>
URI("https://www.google.com") # => #<URI::HTTPS https://www.google.com>

You should either specify the type of URI you want, for example:

params(uri: URI::HTTPS).returns(String)

Or pick a subset and use a union type:

params(uri: T.any(URI::HTTP, URI::HTTPS)).returns(String)
  • Related