Sha256: cc2fb3f8ae5f65baa1f359ea33c833e39cdb7d2e3c57e512ed2a8c1038179be4

Contents?: true

Size: 945 Bytes

Versions: 4

Compression:

Stored size: 945 Bytes

Contents

require 'uri'
require 'net/http'
require 'json'

module LatestStockPrice
  class HttpClient
    def self.make_request(uri)
      response = perform_request(uri)
      parse_response(response.body)
    end

    private

    def self.perform_request(uri)
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true

      request = Net::HTTP::Get.new(uri)
      request["x-rapidapi-key"] = ENV['X_RAPIDAPI_KEY']
      request["x-rapidapi-host"] = ENV['X_RAPIDAPI_HOST']
      response = http.request(request)

      unless response.is_a?(Net::HTTPSuccess)
        raise "Error fetching data: #{response.code} #{response.message}"
      end

      response
    rescue SocketError, Errno::ECONNREFUSED => e
      raise "Network error: #{e.message}"
    end

    def self.parse_response(response_body)
      JSON.parse(response_body)
    rescue JSON::ParserError => e
      raise "Error parsing response: #{e.message}"
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
latest_stock_price-1.0.3 lib/http_client.rb
latest_stock_price-1.0.2 lib/http_client.rb
latest_stock_price-1.0.1 lib/http_client.rb
latest_stock_price-1.0.0 lib/latest_stock_price/http_client.rb