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
25
26
# File 'lib/quarantine/databases/google_sheets.rb', line 22

def fetch_items(table_name)
  parse_rows(spreadsheet.worksheet_by_title(table_name))
rescue GoogleDrive::Error, Google::Apis::Error
  raise Quarantine::DatabaseError
end

#write_items(table_name, items) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/quarantine/databases/google_sheets.rb', line 34

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 do |header|
      match = header.match(/^(extra_)?(.+)/)
      extra, name = match[1..]
      puts "header: #{header}, extra: #{extra}, name: #{name}"
      value = extra ? item['extra_attributes'][name.to_sym] : item[name]
      value.to_s
    end
    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
rescue GoogleDrive::Error, Google::Apis::Error
  raise Quarantine::DatabaseError
end