Class: NBA::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/nba/connection.rb

Overview

Handles HTTP connections to the NBA API

Constant Summary collapse

BASE_URL =

Default base URL for the NBA Stats API

Returns:

  • (String)

    the default base URL

"https://stats.nba.com/stats/".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_url: BASE_URL) ⇒ NBA::Connection

Initializes a new Connection object

Examples:

connection = NBA::Connection.new

Parameters:

  • base_url (String) (defaults to: BASE_URL)

    the base URL for API requests



27
28
29
# File 'lib/nba/connection.rb', line 27

def initialize(base_url: BASE_URL)
  @base_url = base_url
end

Instance Attribute Details

#base_urlString (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the base URL for API requests

Returns:

  • (String)

    the base URL



18
19
20
# File 'lib/nba/connection.rb', line 18

def base_url
  @base_url
end

Instance Method Details

#get(path) ⇒ String

Makes a GET request to the specified path

Examples:

connection.get("teams")

Parameters:

  • path (String)

    the API path to request

Returns:

  • (String)

    the response body



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/nba/connection.rb', line 38

def get(path)
  uri = URI.join(base_url, path)
  hostname = uri.hostname or raise ArgumentError, "Invalid URI: #{uri}"
  request = Net::HTTP::Get.new(uri)
  apply_headers(request)

  Net::HTTP.start(hostname, uri.port, use_ssl: uri.scheme.eql?("https")) do |http|
    response = http.request(request)
    decode_body(response) if response.is_a?(Net::HTTPSuccess)
  end
end