在 Rails 访问 Ruby 中的 Google 云端硬盘电子表格

Access a Google Drive spreadsheet in Ruby on Rails

我正在尝试获取 Google 云端硬盘电子表格的内容,但似乎找不到可以轻松完成此操作的 gem。我试过 google-drive-ruby,但它涉及一个步骤,我必须从 Google 的网站获取授权令牌。这不是很有帮助,因为我必须在服务器端完成所有这些工作。显然 gem 的早期版本中有一个登录方法,但被删除了。

有什么办法吗?我是否必须使用 OAuth 获取令牌并将该令牌传递到 google-drive-ruby?

我设法在 Reddit 上得到了答案。您需要一个服务帐户并与您的服务应用程序的电子邮件共享文档。 p12 密钥也必须存储在某个地方。

# gem install google-api-client -v 0.8.6 # upper versions are not compatible with this code

require "google/api_client"

@email = "email@developer.gserviceaccount.com"
@key = "path/to/key.p12"

key = Google::APIClient::KeyUtils.load_from_pkcs12(@key, 'notasecret')

auth = Signet::OAuth2::Client.new(
  token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
  audience: 'https://accounts.google.com/o/oauth2/token',
  scope: ["https://www.googleapis.com/auth/drive", "https://spreadsheets.google.com/feeds/"].join(' '),
  issuer: @email,
  access_type: 'offline',
  signing_key: key
)

auth.fetch_access_token!
puts auth.access_token