I create this code, using this reference https://developers.google.com/drive/api/quickstart/ruby
class Drive
def initialize
@drive_service = Google::Apis::DriveV3::DriveService.new
@drive_service.client_options.application_name = APPLICATION_NAME
@drive_service.authorization = authorize
end
def create_file
data = { 'name': "My new Sheet #{Time.now.strftime('%d/%m/%Y %H:%M')}",
'mimeType': 'application/vnd.google-apps.spreadsheet' }
@drive_service.create_file(data).execute
end
def share_file
"to be filled"
end
def list_files
response = @drive_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
end
The method list_files
works well, but the create_file
return me this error:
Traceback (most recent call last):
2: from quickstart.rb:79:in `<main>'
1: from quickstart.rb:60:in `create_file'
/home/vagrant/.rvm/gems/ruby-2.7.2/gems/google-api-client-0.53.0/generated/google/apis/drive_v3/service.rb:895:in `create_file': unknown keywords: :name, :mimeType (ArgumentError)
I created it based on this create method reference: https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/DriveV3/DriveService.html#create_file-instance_method but I still can't get it to work, what could be wrong?
I tried changing the creation to: @drive_service.create_file(file_object = data).execute
CodePudding user response:
Let's compare your code,
data = { 'name': "My new Sheet ...
@drive_service.create_file(data).execute
vs. the documented method signature.
`create_file(file_object = nil, enforce_single_parent: nil, ignore_default_visibility: nil, include_permissions_for_view: nil, keep_revision_forever: nil, ocr_language: nil, supports_all_drives: nil, supports_team_drives: nil, use_content_as_indexable_text: nil, fields: nil, quota_user: nil, user_ip: nil, upload_source: nil, content_type: nil, options: nil) {|result, err| ... } ⇒ Google::Apis::DriveV3::File`
- file_object (Google::Apis::DriveV3::File) (defaults to: nil)
The first argument should be an instance of Google::Apis::DriveV3::File
, but you are passing a Hash
.
CodePudding user response:
According to this documentation:
When supplying hashes for request objects. If it is the last argument to a method, some versions of Ruby will interpret the hash as keyword arguments. To prevent this, appending an empty hash as an extra parameter will avoid misinterpretation.
file = {id: '123', title: 'My document', labels: { starred: true }} file = drive.create_file(file) # Raises ArgumentError: unknown keywords: id, title, labels file = drive.create_file(file, {}) # Returns a Drive::File instance
In your code, just add {}
as 2nd parameter for create_file.
From:
@drive_service.create_file(data)
To:
@drive_service.create_file(data, {})
Let me know if this works on your end.