Skip to content

Instantly share code, notes, and snippets.

@fukumame
Last active August 11, 2017 02:54
Show Gist options
  • Select an option

  • Save fukumame/a9a7a50fea2360c5e07d8daafa34eaab to your computer and use it in GitHub Desktop.

Select an option

Save fukumame/a9a7a50fea2360c5e07d8daafa34eaab to your computer and use it in GitHub Desktop.
Google Drive APIへの接続
require 'google/apis/drive_v3'
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'fileutils'
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
APPLICATION_NAME = 'Drive API Ruby Quickstart'
CLIENT_SECRETS_PATH = 'client_secret.json'
# ファイル名もgoogle serviceの名前に合わせて変更する。(この名前は任意の値でOK)
CREDENTIALS_PATH = File.join(Dir.home, '.credentials',
"drive-ruby-quickstart.yaml")
# 他のgoogle serviceにアクセスしたい場合は、ここを変更する
SCOPE = Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY
# main以外のメソッドは他のサービスのアクセスでも再利用可能
def get_authorizer
FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))
client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)
authorizer = Google::Auth::UserAuthorizer.new(
client_id, SCOPE, token_store)
authorizer
end
def retrieve_code
authorizer = get_authorizer
url = authorizer.get_authorization_url(base_url: OOB_URI)
puts "Open the following URL in the browser and enter the resulting code after authorization"
puts url
end
def store_credentials(code)
authorizer = get_authorizer
user_id = 'default'
credentials = authorizer.get_credentials(user_id)
if credentials.nil?
authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI)
end
end
def get_credentials
authorizer = get_authorizer
user_id = 'default'
credentials = authorizer.get_credentials(user_id)
credentials
end
def main
# Initialize the API
service = Google::Apis::DriveV3::DriveService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = get_credentials
# List the 10 most recently modified files.
response = service.list_files(page_size: 10,
fields: 'nextPageToken, files(id, name)')
puts 'Files:'
puts 'No files found' if response.files.empty?
response.files.each do |file|
puts "#{file.name} (#{file.id})"
end
end
#retrieve_code
#code = nil
#store_credentials(code) unless code.nil?
main
@fukumame
Copy link
Copy Markdown
Author

retrieve_codeを実行するとURLが出力される
そのURLをブラウザでアクセスるとcodeが発行される
そのcodeをもとに、store_credentialsを呼ぶと、接続のためのcredentialsが保存される
その後mainを呼ぶと、Driveにアクセスできる

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment