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

Viewed 888

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.

2 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.

Just verified that the following works:

drive.update_file(file_id, { name: new_name })

You no longer need to create a new File object to update the name of an existing file.

Related