Module: Lexdrill::SheetsClient

Defined in:
lib/lexdrill/sheets_client.rb

Overview

Thin wrapper around the Google Sheets API v4 REST endpoints needed by drill export/drill import: create the target tab if it doesn't already exist, clear its contents, write new rows into it, then auto-fit column A's width to the content so long phrases aren't visually truncated; or, for import, read column A back out of an existing tab.

Defined Under Namespace

Classes: ApiError

Constant Summary collapse

BASE_URL =
"https://sheets.googleapis.com/v4/spreadsheets"

Class Method Summary collapse

Class Method Details

.clear(spreadsheet_id, sheet_name, access_token) ⇒ Object



61
62
63
64
# File 'lib/lexdrill/sheets_client.rb', line 61

def self.clear(spreadsheet_id, sheet_name, access_token)
  url = "#{BASE_URL}/#{spreadsheet_id}/values/#{encoded_range(sheet_name)}:clear"
  handle_response(Lexdrill::HTTPClient.json_post(url, body: {}, headers: auth_header(access_token)))
end

.overwrite_sheet(spreadsheet_id, sheet_name, rows, access_token) ⇒ Object



23
24
25
26
27
28
# File 'lib/lexdrill/sheets_client.rb', line 23

def self.overwrite_sheet(spreadsheet_id, sheet_name, rows, access_token)
  sheet_id = ensure_sheet_exists(spreadsheet_id, sheet_name, access_token)
  clear(spreadsheet_id, sheet_name, access_token)
  update(spreadsheet_id, sheet_name, rows, access_token)
  autofit_first_column(spreadsheet_id, sheet_id, access_token)
end

.read_column(spreadsheet_id, sheet_name, access_token) ⇒ Object

Reads column A back out of an existing tab (ignoring any other columns, e.g. show counts from an older export), skipping blank cells.



74
75
76
77
78
# File 'lib/lexdrill/sheets_client.rb', line 74

def self.read_column(spreadsheet_id, sheet_name, access_token)
  url = "#{BASE_URL}/#{spreadsheet_id}/values/#{encoded_range(sheet_name)}"
  data = handle_response(Lexdrill::HTTPClient.json_get(url, headers: auth_header(access_token)))
  data.fetch("values", []).filter_map { |row| row[0]&.strip }.reject(&:empty?)
end

.update(spreadsheet_id, sheet_name, rows, access_token) ⇒ Object



66
67
68
69
70
# File 'lib/lexdrill/sheets_client.rb', line 66

def self.update(spreadsheet_id, sheet_name, rows, access_token)
  url = "#{BASE_URL}/#{spreadsheet_id}/values/#{encoded_range(sheet_name)}?valueInputOption=RAW"
  body = { "range" => quoted_range(sheet_name), "majorDimension" => "ROWS", "values" => rows }
  handle_response(Lexdrill::HTTPClient.json_put(url, body: body, headers: auth_header(access_token)))
end