Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do a rename a file using the Google Drive API for Ruby?

This seems like a basic question, but I'm well into my second day now :(

I'm using the Google Drive Ruby Api here: https://github.com/google/google-api-ruby-client but the basic file examples in the README appear to be well out of date. In particular, calls to Drive.update_file don't take anything like the parameters shown.

So far, I can get hold of an authorized DriveService:

drive = Google::Apis::DriveV3::DriveService.new
drive.authorization = Google::Auth.get_application_default(['https://www.googleapis.com/auth/drive'])

I can get a File:

file_id = 'string-of-stuff'
file = drive.get_file file_id

I can set attributes on the File object that look okay:

file.update!(name: 'My new name')

But, I can't figure out how to get the update/patch to actually work after that. The README suggests drive.update_file(file), but that just explodes with a type error.

TypeError: Can't convert Google::Apis::DriveV3::File into String or Array.

Looking at the code, #update_file actually expects a file_id as the first param.

I've tried all sorts of variations based on the README, like:

drive.update_file(file_id, {name: 'New name'})

or:

drive.update_file(file_id, {title: 'New name'})

or (looking at the code):

drive.update_file(file_id, fields: {title: 'New name'})

or even:

drive.update_file(file_id, file)

which explodes with:

Google::Apis::ClientError: fieldNotWritable: The resource body includes fields which are not directly writable.

But nothing works for me. Has anyone used this library? Everything else seems fairly straightforward, but this is just HARD.

like image 664
Nello Avatar asked Sep 22 '17 00:09

Nello


People also ask

How do you rename a file in Google Drive?

Next to a file you want to rename, tap the Down arrow . Tap Rename. Enter a new name. Tap OK.

How do I create a Google Drive folder in Google Drive API?

To create a folder, use the files. create method with the application/vnd. google-apps. folder MIME type and a title.


1 Answers

Well, after much more trial-and-error, the ONLY way this API works is with a new File object. If you use get_file to get your File, then you end up with an object that has an unwritable id field.

So, this - and only this - appears to work:

drive.update_file(file_id, Google::Apis::DriveV3::File.new(name: name))

Sigh.

like image 159
Nello Avatar answered Oct 06 '22 04:10

Nello