Module: GoogleSheetReader

Defined in:
lib/google_sheet_reader.rb,
lib/google_sheet_reader/version.rb

Defined Under Namespace

Classes: EmptyFileError, FileDownloadError, FileDownloadLinkError, FileRetrievalError

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.client(options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/google_sheet_reader.rb', line 8

def self.client(options = {})
  app_name = options[:app_name]
  email_address = options[:email_address]
  key_file_path = options[:key_file_path]

  key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file_path, 'notasecret')
  asserter = Google::APIClient::JWTAsserter.new(email_address, 'https://www.googleapis.com/auth/drive', key)
  google_api_client = Google::APIClient.new({:application_name => app_name, :application_version => "1.0"})
  google_api_client.authorization = asserter.authorize()
  return google_api_client
end

.extract(spreadsheet_id, options = {}) ⇒ Object

Extract data from a Google Drive spreadsheet.

Examples:

GoogleSheetReader.extract(file_id, opts)

Parameters:

  • spreadsheet_id (String)
  • options (Hash) (defaults to: {})
    String

    app_name

  • options (Hash) (defaults to: {})
    String

    email_address

  • options (Hash) (defaults to: {})
    String

    key_file_path

  • options (Hash) (defaults to: {})
    Proc

    extraction_procedure

Raises:



30
31
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
58
59
60
61
62
63
64
65
66
# File 'lib/google_sheet_reader.rb', line 30

def self.extract(spreadsheet_id, options = {})
  app_name = options[:app_name]
  email_address = options[:email_address]
  key_file_path = options[:key_file_path]
  extraction_procedure = options[:extraction_procedure]

  puts "CONNECTING TO GOOGLE DRIVE ..."

  google_api_client = self.client(options)
  drive = google_api_client.discovered_api('drive', 'v2')

  get_request_result = google_api_client.execute(
    :api_method => drive.files.get,
    :parameters => { 'fileId' => spreadsheet_id }
  )
  raise FileRetrievalError unless get_request_result.status == 200

  file = get_request_result.data
  download_url = file.exportLinks["text/csv"]
  raise FileDownloadLinkError unless download_url

  download_request_result = google_api_client.execute(:uri => download_url)
  raise FileDownloadError unless download_request_result.status == 200

  file_contents = download_request_result.body
  csv_result = CSV.parse(file_contents, headers:true)
  #headers = csv_result.headers

  raise EmptyFileError.new("This spreadsheet has no data. Please add rows.") unless csv_result.any?

  csv_result.each do |row|
    extraction_procedure.call(row)
  end

  puts "PARSED #{csv_result.count} ROWS"
  return {:status => "SUCCESS", :row_count => csv_result.count}
end