ruby-on-rails - Google Calendar API 插入方法不适用于 Ruby
问题描述
我正在尝试在我的 Ruby 项目中使用 Google Calendar API,但在尝试使用 API 中的插入时遇到了问题。当我在https://developers.google.com/calendar/v3/reference/events/insert#examples上尝试示例代码时,我最终得到了一个错误。
insertEvent.rb:2:in `<main>': uninitialized constant Google (NameError)
如果我将此示例代码粘贴在此页面 https://developers.google.com/calendar/quickstart/ruby上的 quickstart.rb 之后,我将收到此错误:
quickstart.rb:84:in `<main>': undefined local variable or method `client' for main:Object (NameError)
谷歌在这里没有给我客户端变量的定义,所以我没有在这里插入什么。我是 Ruby 的新手,非常感谢您的帮助。
这是我陷入的代码
result = client.insert_event('primary', event)
puts "Event created: #{result.html_link}"
解决方案
是的,客户没有定义。试试这个示例代码
https://github.com/googleapis/google-api-ruby-client/blob/master/samples/cli/lib/samples/calendar.rb
和
https://developers.google.com/calendar/quickstart/ruby
这里的重要部分:
require 'google/apis/calendar_v3'
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'fileutils'
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'.freeze
APPLICATION_NAME = 'Google Calendar API Ruby Quickstart'.freeze
CREDENTIALS_PATH = 'credentials.json'.freeze
TOKEN_PATH = 'token.yaml'.freeze
SCOPE = Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY
def authorize
client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)
token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)
authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)
# figure out your user_id
user_id = 'default'
credentials = authorizer.get_credentials(user_id)
if credentials.nil?
url = authorizer.get_authorization_url(base_url: OOB_URI)
puts 'Open the following URL in the browser and enter the ' \
"resulting code after authorization:\n" + url
code = gets
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI
)
end
credentials
end
calendar = Google::Apis::CalendarV3::CalendarService.new
calendar.client_options.application_name = APPLICATION_NAME
calendar.authorization = authorize
event = {
summary: 'Events',
attendees: [
{email: 'lpage@example.com'},
{email: 'sbrin@example.com'},
],
start: {
date_time: '2015-05-28T09:00:00-07:00',
time_zone: 'America/Los_Angeles',
},
end: {
date_time: '2015-05-28T17:00:00-07:00',
time_zone: 'America/Los_Angeles',
}
}
event = calendar.insert_event('primary', event, send_notifications: true)
并且不要忘记先运行它:
gem install google-api-client
并使用正确的身份验证信息创建这些文件
credentials.json
token.yaml
并找出你的user_id
.
推荐阅读
- node.js - Facebook 更新图像 API
- gnuplot - 将acspline与数据填充曲线相结合
- r - 2 for 循环下的向量
- javascript - 在 python3 中使用 webbrowser 播放 YouTube 视频
- java - Maven Central 上的 J2EE jar 发生了什么变化?
- mysql - 将表列更改为生成日期 - 语法问题
- python - 数据框仅显示来自列分区的选定结果
- javascript - 这对于 JavaScript 绑定方法的 Polyfill 来说是一个可接受的解决方案吗?
- java - 从数组中获取重复项并将重复项复制到另一个数组中
- c# - Npgsql 异常:列 c.consrc 不存在