如何使用Google Drive API for Ruby重命名文件?

5
这似乎是一个基础问题,但我已经花了两天时间了 :(
我在这里使用Google Drive Ruby API:https://github.com/google/google-api-ruby-client,但README中的基本文件示例似乎已经过时了。特别是,对Drive.update_file的调用与显示的参数完全不同。
到目前为止,我可以获取授权的DriveService:
drive = Google::Apis::DriveV3::DriveService.new
drive.authorization = Google::Auth.get_application_default(['https://www.googleapis.com/auth/drive'])

我可以获取文件:

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

我可以在文件对象上设置属性,使其看起来不错:
file.update!(name: 'My new name')

但是,之后我就无法弄清楚如何让更新/补丁真正起作用。README建议使用drive.update_file(file),但这只会出现类型错误。

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

从代码来看,#update_file 期望第一个参数传递一个 file_id

我根据自述文件尝试了各种变化,比如:

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

or:

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

或者(查看代码):
drive.update_file(file_id, fields: {title: 'New name'})

甚至更多的是:
drive.update_file(file_id, file)

其中包含以下内容:

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

但是对我来说没有任何作用。有人使用过这个库吗?其他东西都相当简单,但是这个就很难。


嗯,drive.update_file(file_id, name: 'New name')(或等价的 drive.update_file(file_id, { name: 'New name' }))应该可以工作,drive.update_file(file_id, file) 也应该可以。您确定 file_id 指的是可重命名的对象吗?(“请注意,对于不可变项(如团队驱动器的顶级文件夹、My Drive 根文件夹和应用程序数据文件夹),名称是恒定的。”)错误是针对两种形式还是只针对最后一种形式?如果不是,请问当您执行 drive_update(file_id, name: "New name") 时会发生什么? - Amadan
嗨@Amadan,drive.update_file(file_id, { name: 'New name' })drive.update_file(file_id, name: 'New name')都会出现ArgumentError:unknown keyword: name,来自/usr/local/var/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/google-api-client-0.14.1/generated/google/apis/drive_v3/service.rb:948:in update_file - Nello
2个回答

6

经过多次试验和错误,发现这个API只能使用一个新的File对象来工作。如果你使用get_file获取File,那么你得到的是一个具有不可写id字段的对象。

因此,只有以下代码似乎有效:

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

唉。


当然,如果你在团队驱动器上,不要忘记将神奇的 supports_team_drives: true 参数添加到你的 update_file 方法中,否则它会抱怨找不到文件。唉。 - Cyril Duchon-Doris

0

刚刚验证了以下代码可以正常工作:

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

您不再需要创建一个新的File对象来更新现有文件的名称。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接