Skip to content

Instantly share code, notes, and snippets.

@cabb
Created May 7, 2025 12:42
Show Gist options
  • Save cabb/0422ab6b8450352aac915346b1e1435d to your computer and use it in GitHub Desktop.
Save cabb/0422ab6b8450352aac915346b1e1435d to your computer and use it in GitHub Desktop.
Define ssl_context for persistent http connection to not verify SSL certificates
class API
# Defines the base path for the API endpoint
API_PATH = 'api/v2'
def initialize(host:, username:, password:, api_https:, timeout: nil)
# Determine protocol based on the 'api_https' flag
scheme = api_https ? 'https' : 'http'
# Construct the base URL using the scheme, host, and API path
base_url = "#{scheme}://#{host}#{API_PATH}"
if api_https
# Prepare SSL context with no certificate verification (not recommended for production)
ctx = OpenSSL::SSL::SSLContext.new
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
# Configure default HTTP options only if using HTTPS
HTTP.default_options = HTTP::Options.new({ ssl_context: ctx, ssl: true })
end
# Set default headers, including accept and user-agent
headers = { accept: 'application/json' }
headers[:'user-agent'] = "ruby-api-agent"
# Initialize a persistent HTTP connection with basic authentication and auto-follow redirects
@http = HTTP.persistent(@base_url)
.headers(headers)
.basic_auth(user: username, pass: password)
.follow
# Apply a read timeout if specified
if timeout
@http.timeout(
read: timeout
)
end
# Log that the HTTP connection has been established
logger.debug "HTTP connection established to #{base_url}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment