Class: GoogleSheets::Spreadsheet

Inherits:
Object
  • Object
show all
Defined in:
lib/google_sheets/spreadsheet.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(service, key) ⇒ Spreadsheet

Returns a new instance of Spreadsheet


9
10
11
12
13
# File 'lib/google_sheets/spreadsheet.rb', line 9

def initialize service, key
  @key = key
  @service = service
  load_spreadsheet
end

Instance Attribute Details

#keyString (readonly)

the spreadsheet key

Returns:

  • (String)

7
8
9
# File 'lib/google_sheets/spreadsheet.rb', line 7

def key
  @key
end

Instance Method Details

#add_sheet(title, values: []) ⇒ Sheet

Returns:


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
# File 'lib/google_sheets/spreadsheet.rb', line 34

def add_sheet title, values: []
  add_sheet_request = Google::Apis::SheetsV4::AddSheetRequest.new
  add_sheet_request.properties = Google::Apis::SheetsV4::SheetProperties.new
  add_sheet_request.properties.title = title

  batch_update_spreadsheet_request = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new
  batch_update_spreadsheet_request.requests = Google::Apis::SheetsV4::Request.new

  batch_update_spreadsheet_request_object = [ add_sheet: add_sheet_request ]
  batch_update_spreadsheet_request.requests = batch_update_spreadsheet_request_object

  response = @service.batch_update_spreadsheet(@key, batch_update_spreadsheet_request)

  resp = append_to_sheet(title, values) if values&.any?

  add_sheet = response.replies[0].add_sheet

  sheet = Sheet.new(@service, add_sheet, self)

  sheet.values = values if values&.any?

  self.sheets << sheet

  sheet
end

#load_spreadsheetObject Also known as: refresh!

loads the spreadsheet from google sheets


16
17
18
19
20
# File 'lib/google_sheets/spreadsheet.rb', line 16

def load_spreadsheet
  @sheets = nil
  @spreadsheet = @service.get_spreadsheet(@key)
  @properties = @spreadsheet.properties.to_h
end

#sheetsArray(Sheet)

Returns:


26
27
28
29
30
# File 'lib/google_sheets/spreadsheet.rb', line 26

def sheets
  @sheets ||= @spreadsheet.sheets.map do |sheet|
    Sheet.new(@service, sheet, self)
  end
end