Module: NBA::ResponseParser

Defined in:
lib/nba/response_parser.rb

Overview

Parses NBA API responses and builds collections of objects

This module consolidates the common pattern of parsing JSON responses from the NBA Stats API, extracting result sets, and building objects from header/row pairs.

Class Method Summary collapse

Class Method Details

.parse(response, result_set: nil) {|Hash| ... } ⇒ Collection

Parses an API response and returns a collection of objects

Examples:

ResponseParser.parse(response, result_set: "PlayerStats") { |data| Player.new(**data) }

Parameters:

  • response (String, nil)

    the JSON response body

  • result_set (String, nil) (defaults to: nil)

    the name of the result set to extract (nil for first)

Yields:

  • (Hash)

    yields each row as a hash with header keys

Returns:



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/nba/response_parser.rb', line 20

def self.parse(response, result_set: nil, &builder)
  return Collection.new unless response

  data = parse_json(response)
  return Collection.new unless data

  result = find_result_set(data, result_set)
  return Collection.new unless result

  build_collection(result, &builder)
end

.parse_single(response, result_set: nil) {|Hash| ... } ⇒ Object?

Parses an API response and returns a single object

Examples:

ResponseParser.parse_single(response) { |data| Player.new(**data) }

Parameters:

  • response (String, nil)

    the JSON response body

  • result_set (String, nil) (defaults to: nil)

    the name of the result set to extract

Yields:

  • (Hash)

    yields the first row as a hash with header keys

Returns:

  • (Object, nil)

    the parsed object or nil



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/nba/response_parser.rb', line 41

def self.parse_single(response, result_set: nil)
  return unless response

  data = parse_json(response)
  return unless data

  result = find_result_set(data, result_set)
  return unless result

  headers = result["headers"]
  row = result.dig("rowSet", 0)
  return unless headers && row

  yield zip_to_hash(headers, row)
end

.zip_to_hash(headers, row) ⇒ Hash

Zips headers and row into a hash

Examples:

ResponseParser.zip_to_hash(["NAME", "AGE"], ["LeBron", 39])
#=> {"NAME" => "LeBron", "AGE" => 39}

Parameters:

  • headers (Array<String>)

    the column headers

  • row (Array)

    the row data

Returns:

  • (Hash)

    a hash with header keys and row values



66
67
68
# File 'lib/nba/response_parser.rb', line 66

def self.zip_to_hash(headers, row)
  headers.zip(row).to_h
end