Search code examples
rubynet-http

Automatically get the default port for request


I currently have the following code:

    if protocol == 'http'
      port = Net::HTTP.http_default_port()
      endpoint = Net::HTTP.new(host, port)
    else
      port = Net::HTTP.https_default_port()
      endpoint = Net::HTTP.new(host, port)
      endpoint.use_ssl = true
    end
    request = Net::HTTP::Get.new("/item/#{item}")
    request['Authorization'] = "Bearer #{key}"
    response = endpoint.request(request)

Is there a way to simplify this so that I do not have to decide the default port to use for myself?


Solution

  • You would use ruby's dynamic dispatching.

    port = Net::HTTP.send("#{protocol}_default_port")
    endpoint = Net::HTTP.new(host, port)
    endpoint.use_ssl = protocol == 'https'
    
    request = Net::HTTP::Get.new("/item/#{item}")
    request['Authorization'] = "Bearer #{key}"
    response = endpoint.request(request)
    

    OR in more elegant way:

    path = URI('https://example.com')
    
    Net::HTTP.start(path.host, path.port, use_ssl: path.scheme == 'https') do |http|
      request = Net::HTTP::Get.new path
      request['Authorization'] = "Bearer #{key}"
      response = http.request(request)
    end