Class: BabelBot::CSVLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/babel_bot/csv_loader.rb

Constant Summary collapse

API_VERSION =
"v2"

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ CSVLoader

Returns a new instance of CSVLoader.



19
20
21
# File 'lib/babel_bot/csv_loader.rb', line 19

def initialize(config={})
  @config = config;
end

Instance Method Details

#app_flowObject



84
85
86
87
88
89
90
# 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_clientObject



28
29
30
31
32
33
34
# 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?Boolean

Returns:

  • (Boolean)


76
77
78
# File 'lib/babel_bot/csv_loader.rb', line 76

def cached_auth_exists?
  file_storage.authorization
end

#clientObject



69
70
71
72
73
74
# 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_secretsObject



92
93
94
# File 'lib/babel_bot/csv_loader.rb', line 92

def client_secrets
  @client_secrets ||= Google::APIClient::ClientSecrets.load
end

#driveObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 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_storageObject



80
81
82
# File 'lib/babel_bot/csv_loader.rb', line 80

def file_storage
  @file_storage ||= Google::APIClient::FileStorage.new(@config["credentialsCachePath"])
end

#loadObject



23
24
25
26
# File 'lib/babel_bot/csv_loader.rb', line 23

def load
  authorize_client
  load_csv
end

#load_csvObject



54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/babel_bot/csv_loader.rb', line 54

def load_csv
   = client.execute!(
    api_method: drive.files.get,
    parameters: { "fileId" => @config["fileId"] }
  )

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

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