Class: AdLocalize::Repositories::DriveRepository

Inherits:
Object
  • Object
show all
Defined in:
lib/ad_localize/repositories/drive_repository.rb

Instance Method Summary collapse

Constructor Details

#initializeDriveRepository

Returns a new instance of DriveRepository.



5
6
7
8
9
10
11
12
13
14
# File 'lib/ad_localize/repositories/drive_repository.rb', line 5

def initialize
  @drive_service = Google::Apis::DriveV3::DriveService.new
  @sheet_service = Google::Apis::SheetsV4::SheetsService.new
  if ENV['GOOGLE_APPLICATION_CREDENTIALS']
    drive_scope = [Google::Apis::DriveV3::AUTH_DRIVE_READONLY]
    sheet_scope = [Google::Apis::SheetsV4::AUTH_SPREADSHEETS_READONLY]
    @drive_service.authorization = Google::Auth.get_application_default(drive_scope)
    @sheet_service.authorization = Google::Auth.get_application_default(sheet_scope)
  end
end

Instance Method Details

#download_all_sheets(spreadsheet_id:) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/ad_localize/repositories/drive_repository.rb', line 34

def download_all_sheets(spreadsheet_id:)
  begin
    spreadsheet = @sheet_service.get_spreadsheet(spreadsheet_id)
    sheet_ids = spreadsheet.sheets.map { |sheet| sheet.properties.sheet_id }
    LOGGER.debug("#{sheet_ids.size} sheets in the spreadsheet")
    download_sheets_by_id(spreadsheet_id: spreadsheet_id, sheet_ids: sheet_ids)
  rescue => e
    LOGGER.error("Cannot download sheets. Error: #{e.message}")
    []
  end
end

#download_sheets_by_id(spreadsheet_id:, sheet_ids:) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/ad_localize/repositories/drive_repository.rb', line 16

def download_sheets_by_id(spreadsheet_id:, sheet_ids:)
  sheet_ids.filter_map do |sheet_id|
    begin
      url = export_url(spreadsheet_id: spreadsheet_id, sheet_id: sheet_id)
      string = @drive_service.http(:get, url, options: { retries: 5, max_elapsed_time: 120 })
      next unless string

      tempfile = Tempfile.new
      tempfile.write(string)
      tempfile.rewind
      tempfile
    rescue => e
      LOGGER.error("Cannot download sheet with id #{sheet_id}. Error: #{e.message}")
      nil
    end
  end
end