tbeseda
tbeseda

Reputation: 1857

How can I create a Google spreadsheet for a user with Ruby, as a Google Apps Admin?

I'd like to automate the creation of documents for users of our Google Apps service.
Considerations:

Is this achievable with an existing Ruby library? (Most use 2-legged auth to accomplish this as the user, not as an admin.)

Upvotes: 3

Views: 1436

Answers (1)

tbeseda
tbeseda

Reputation: 1857

I was able to accomplish this with a "Service Account" and Google's (alpha) gem google-api-client. Here is a Ruby class, sampled from disparate Google documentation, that takes an user's email (from the Google Apps domain you manage) when instantiated.

require 'google/api_client'

class GoogleDriveConnection
  def initialize(user_email=nil)
    @client = Google::APIClient.new
    @drive = @client.discovered_api('drive', 'v2')

    key_file_name = '<DOWNLOADED WHEN CREATING A SERVICE ACCOUNT>.p12'
    key = Google::APIClient::PKCS12.load_key("#{Rails.root.to_s}/config/#{key_file_name}", 'notasecret')

    asserter = Google::APIClient::JWTAsserter.new(
      '<THE EMAIL ADDRESS OF YOUR SERVICE ACCOUNT>',
      'https://www.googleapis.com/auth/drive',
    key)

    @client.authorization = asserter.authorize(user_email)
  end

  def insert_file(title, description, parent_id, mime_type, file_name)
    file = @drive.files.insert.request_schema.new({
      'title' => title,
      'description' => description,
      'mimeType' => mime_type
    })
    # Set the parent folder.
    if parent_id
      file.parents = [{'id' => parent_id}]
    end
    media = Google::APIClient::UploadIO.new(file_name, mime_type)
    result = @client.execute(
      :api_method => @drive.files.insert,
      :body_object => file,
      :media => media,
      :parameters => {
        'uploadType' => 'multipart',
        'convert' => true,
        'alt' => 'json'})
    if result.status == 200
      return result.data
    else
      puts "An error occurred: #{result.data['error']['message']}"
      return nil
    end
  end

  def list_files
    result = @client.execute!(:api_method => @drive.files.list)
    result.data.to_hash
  end

  def get_file(file_id)
    result = @client.execute!(
      :api_method => @drive.files.get,
      :parameters => { 'fileId' => file_id })
    result.data.to_hash
  end

  private

    def token
      @client.authorization.access_token
    end
end

Usage is simple enough:

g = GoogleDriveConnection.new('[email protected]')
g.insert_file('My file', 'File stuff', nil, 'text/csv', "#{Rails.root}/tmp/test.csv")

* Creating a Service Account and managing the "API Project" was tricky. This guide seemed to be most useful.

Upvotes: 1

Related Questions