Class: Quarantine::Databases::GoogleSheets

Inherits:
Base
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/quarantine/databases/google_sheets.rb

Constant Summary

Constants inherited from Base

Base::Item

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ GoogleSheets

Returns a new instance of GoogleSheets.



15
16
17
18
19
# File 'lib/quarantine/databases/google_sheets.rb', line 15

def initialize(options)
  super()

  @options = options
end

Instance Method Details

#fetch_items(table_name) ⇒ Object



22
23
24
# File 'lib/quarantine/databases/google_sheets.rb', line 22

def fetch_items(table_name)
  parse_rows(spreadsheet.worksheet_by_title(table_name))
end

#write_items(table_name, items) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/quarantine/databases/google_sheets.rb', line 32

def write_items(table_name, items)
  worksheet = spreadsheet.worksheet_by_title(table_name)
  headers = worksheet.rows.first.reject(&:empty?)
  new_rows = []

  # Map existing ID to row index
  parsed_rows = parse_rows(worksheet)
  indexes = Hash[parsed_rows.each_with_index.map { |item, idx| [item['id'], idx] }]

  items.each do |item|
    cells = headers.map { |header| item[header].to_s }
    row_idx = indexes[item['id']]
    if row_idx
      # Overwrite existing row
      headers.each_with_index do |_header, col_idx|
        worksheet[row_idx + 2, col_idx + 1] = cells[col_idx]
      end
    else
      new_rows << cells
    end
  end

  # Insert any items whose IDs weren't found in existing rows at the end
  worksheet.insert_rows(parsed_rows.count + 2, new_rows)
  worksheet.save
end