class BabelBot::CSVLoader

Constants

API_VERSION

Public Class Methods

new(config={}) click to toggle source
# File lib/babel_bot/csv_loader.rb, line 19
def initialize(config={})
  @config = config;
end

Public Instance Methods

app_flow() click to toggle source
# File lib/babel_bot/csv_loader.rb, line 84
def app_flow
  @app_flow ||= Google::APIClient::InstalledAppFlow.new(
    client_id: client_secrets.client_id,
    client_secret: client_secrets.client_secret,
    scope: ["https://www.googleapis.com/auth/drive"]
  )
end
authorize_client() click to toggle source
# File lib/babel_bot/csv_loader.rb, line 28
def authorize_client
  if cached_auth_exists?
    client.authorization = file_storage.authorization
  else
    client.authorization = app_flow.authorize(file_storage)
  end
end
cached_auth_exists?() click to toggle source
# File lib/babel_bot/csv_loader.rb, line 76
def cached_auth_exists?
  file_storage.authorization
end
client() click to toggle source
# File lib/babel_bot/csv_loader.rb, line 69
def client
  @client ||= Google::APIClient.new(
    application_name: @config["googleAppName"] || "String File Generator",
    application_version: BabelBot::VERSION
  )
end
client_secrets() click to toggle source
# File lib/babel_bot/csv_loader.rb, line 92
def client_secrets
  @client_secrets ||= Google::APIClient::ClientSecrets.load
end
drive() click to toggle source
# File lib/babel_bot/csv_loader.rb, line 36
def drive
  return @drive if @drive

  api_cache_file_path = @config["apiCachePath"]
  if File.exists?(api_cache_file_path)
    File.open(api_cache_file_path) do |file|
      @drive = Marshal.load(file)
    end
  else
    @drive = client.discovered_api("drive", API_VERSION)
    File.open(api_cache_file_path, "w") do |file|
      Marshal.dump(@drive, file)
    end
  end

  @drive
end
file_storage() click to toggle source
# File lib/babel_bot/csv_loader.rb, line 80
def file_storage
  @file_storage ||= Google::APIClient::FileStorage.new(@config["credentialsCachePath"])
end
load() click to toggle source
# File lib/babel_bot/csv_loader.rb, line 23
def load
  authorize_client
  load_csv
end
load_csv() click to toggle source
# File lib/babel_bot/csv_loader.rb, line 54
def load_csv
  file_metadata_result = client.execute!(
    api_method: drive.files.get,
    parameters: { "fileId" => @config["fileId"] }
  )

  raise "Error requesting CSV" unless file_metadata_result.status == 200

  csv_raw_data = client.execute!(
    http_method: :get,
    uri: file_metadata_result.data.export_links["text/csv"]
  )
  CSV.parse(csv_raw_data.body, {headers: true})
end