Class: Altertable::Adapters::NetHttpAdapter

Inherits:
Base
  • Object
show all
Defined in:
lib/altertable/adapters.rb,
sig/altertable/adapters.rbs

Instance Method Summary collapse

Constructor Details

#initialize(base_url:, timeout:, headers: {}, proxy: nil) ⇒ NetHttpAdapter

proxy left unset (default) follows Net::HTTP's own env-based auto-detection (HTTP_PROXY/HTTPS_PROXY/NO_PROXY). Pass false to disable proxying entirely for fixed, trusted destinations, or a URI string to force a specific proxy.

Parameters:

  • base_url: (String)
  • timeout: (Integer, Float)
  • headers: (::Hash[String, String]) (defaults to: {})
  • proxy: (String, bool, nil) (defaults to: nil)


88
89
90
91
92
93
94
# File 'lib/altertable/adapters.rb', line 88

def initialize(base_url:, timeout:, headers: {}, proxy: nil)
  super(base_url: base_url, timeout: timeout, headers: headers)
  require "net/http"
  require "uri"
  @uri = URI.parse(@base_url)
  @proxy = proxy
end

Instance Method Details

#post(path, body: nil, params: {}) ⇒ Response

Parameters:

  • path (String)
  • body: (String, nil) (defaults to: nil)
  • params: (::Hash[Symbol | String, untyped]) (defaults to: {})

Returns:



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/altertable/adapters.rb', line 96

def post(path, body: nil, params: {})
  uri = URI.join(@uri, path)
  uri.query = URI.encode_www_form(params) unless params.empty?

  req = Net::HTTP::Post.new(uri)
  @headers.each { |k, v| req[k] = v }
  req.body = body if body

  Net::HTTP.start(uri.host, uri.port, *proxy_start_args, use_ssl: uri.scheme == "https", open_timeout: @timeout, read_timeout: @timeout) do |http|
    resp = http.request(req)
    Response.new(resp.code.to_i, resp.body, resp.to_hash)
  end
rescue SocketError, Net::OpenTimeout, Net::ReadTimeout => e
  raise Altertable::NetworkError.new("Timeout: #{e.message}", e)
rescue StandardError => e
  raise Altertable::NetworkError.new(e.message, e)
end

#proxy_start_args::Array[untyped]

Net::HTTP.start's p_addr defaults to :ENV; returning [] here preserves that. Passing an explicit nil p_addr (i.e. [nil]) is how Net::HTTP disables proxying.

Returns:

  • (::Array[untyped])


118
119
120
121
122
123
124
# File 'lib/altertable/adapters.rb', line 118

def proxy_start_args
  return [] if @proxy.nil?
  return [nil] if @proxy == false

  proxy_uri = URI.parse(@proxy)
  [proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password]
end