Refresh samples + add new ones for YouTube, Analytics

This commit is contained in:
Steve Bazyl 2016-01-07 11:41:45 -08:00
parent 1715fc9945
commit fd4ff04266
15 changed files with 622 additions and 165 deletions

View File

@ -205,6 +205,16 @@ result = translate.list_translations(source: 'en', target: 'es', q: 'Hello world
puts result.translations.first.translated_text puts result.translations.first.translated_text
``` ```
## Samples
Samples for versions 0.9 and onward can be found in the `samples` directory.
Contributions for additional samples are welcome. See [CONTRIBUTING](CONTRIBUTING.md).
Samples for previous versions can be found in the
[google-api-ruby-client-samples](https://github.com/google/google-api-ruby-client-samples)
repository.
## Generating APIs ## Generating APIs
For [Cloud Endpoints](https://cloud.google.com/endpoints/) or other APIs not included in the gem, ruby code can be For [Cloud Endpoints](https://cloud.google.com/endpoints/) or other APIs not included in the gem, ruby code can be

6
samples/Gemfile Normal file
View File

@ -0,0 +1,6 @@
source 'https://rubygems.org'
gem 'google-api-client', '~> 0.9.pre4'
gem 'thor', '~> 0.19'
gem 'os', '~> 0.9'
gem 'dotenv'

51
samples/README.md Normal file
View File

@ -0,0 +1,51 @@
# API Samples
This directory contains a small but growing collection of samples for various
APIs. Each sample can be run on the command line from the `google-api-samples`
script.
Contributions of new samples are welcome.
# Setup
Depending on which particular samples you want to run, different
steps may be required. Some samples, like Pub/Sub, require a service account,
others like Drive, Calendar, and YouTube require an OAuth Client ID. And in
some cases like Translate, only an API key is needed.
* Create a project at https://console.developers.google.com
* Go to the `API Manager` and enable the APIs you'd like to try
* Go to `Credentials` and create the appropriate type of credential for the sample
* For keys, use 'Server key' as the type
* For OAuth Client IDs, use 'Other' as the type
* For service accounts, use the 'JSON' key type
Additional details on how to enable APIs and create credentials can be
found in the help guide in the console.
## Example Environment Settings
For convenience, application credentials can be read from the shell environment
or placed in a .env file.
After setup, your .env file might look something like:
```
GOOGLE_API_KEY=AIzaSyC6GvjvPlEzJpTW2bW2t0MPHXXXXXXXXXX
GOOGLE_CLIENT_ID=479164972499-i7j6av7bp2s4on5ltb7pjXXXXXXXXXX.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=JBotCTG5biFWGzXXXXXXXXXX
GOOGLE_APPLICATION_CREDENTIALS=~/ruby-samples-cred.json
```
# Running the samples
To list the available sample modules, run the script:
```
google-api-samples
```
To get help on a specific set of samples, run:
```
google-api-samples help <module>
```

View File

@ -1,43 +0,0 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'googleauth'
require 'google/apis/calendar_v3'
Calendar = Google::Apis::CalendarV3
calendar = Calendar::CalendarService.new
calendar.authorization = Google::Auth.get_application_default([Calendar::AUTH_CALENDAR])
# Create an event, adding any emails listed in the command line as attendees
event = Calendar::Event.new(summary: 'A sample event',
location: '1600 Amphitheatre Parkway, Mountain View, CA 94045',
attendees: ARGV.map { |email| Calendar::EventAttendee.new(email: email) },
start: Calendar::EventDateTime.new(date_time: DateTime.parse('2015-12-31T20:00:00')),
end: Calendar::EventDateTime.new(date_time: DateTime.parse('2016-01-01T02:00:00')))
event = calendar.insert_event('primary', event, send_notifications: true)
puts "Created event '#{event.summary}' (#{event.id})"
# List upcoming events
events = calendar.list_events('primary', max_results: 10, single_events: true,
order_by: 'startTime', time_min: Time.now.iso8601)
puts "Upcoming events:"
events.items.each do |event|
start = event.start.date || event.start.date_time
puts "- #{event.summary} (#{start}) (ID: #{event.id})"
end
# Delete the event we created earlier
calendar.delete_event('primary', event.id, send_notifications: true)
puts "Event deleted"

View File

@ -1,47 +0,0 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Pass all auth variables to .env file
# Read more about auth on https://developers.google.com/drive/web/about-auth
# For example, in my case I added GOOGLE_APPLICATION_CREDENTIALS=credentials.json
require 'dotenv'
Dotenv.load
require 'tempfile'
require 'googleauth'
require 'google/apis/drive_v2'
Drive = Google::Apis::DriveV2
drive = Drive::DriveService.new
drive.authorization = Google::Auth.get_application_default([Drive::AUTH_DRIVE])
# Insert a file
file = drive.insert_file({title: 'drive.rb'}, upload_source: __FILE__)
puts "Created file #{file.title} (#{file.id})"
# Search for it
files = drive.list_files(q: "title = 'drive.rb'")
puts "Search results:"
files.items.each do |file|
puts "- File: #{file.title} (#{file.id})"
end
# Read it back
tmp = drive.get_file(file.id, download_dest: Tempfile.new('drive'))
# Delete it
drive.delete_file(file.id)
puts "File deleted"

32
samples/google-api-samples Executable file
View File

@ -0,0 +1,32 @@
#!/usr/bin/env ruby
$:.unshift(File.expand_path("../lib", __FILE__))
require 'thor'
require 'dotenv'
# Small script to allow executing samples from the command line.
# Each sample is loaded as a subcommand.
#
# Example usage:
#
# google-api-samples drive upload myfile.txt
#
#
class App < Thor
# Load all the samples and register them as subcommands
Dir.glob('./lib/samples/*.rb').each do |file|
require file
end
Samples.constants.each do |const|
desc const.downcase, "#{const} samples"
subcommand const.downcase, Samples.const_get(const)
end
end
Dotenv.load
App.start(ARGV)

94
samples/lib/base_cli.rb Normal file
View File

@ -0,0 +1,94 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'fileutils'
require 'thor'
require 'os'
# Base command line module for samples. Provides authorization support,
# either using application default credentials or user authorization
# depending on the use case.
class BaseCli < Thor
include Thor::Actions
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
class_option :user, :type => :string
class_option :api_key, :type => :string
no_commands do
# Returns the path to the client_secrets.json file.
def client_secrets_path
return ENV['GOOGLE_CLIENT_SECRETS'] if ENV.has_key?('GOOGLE_CLIENT_SECRETS')
return well_known_path_for('client_secrets.json')
end
# Returns the path to the token store.
def token_store_path
return ENV['GOOGLE_CREDENTIAL_STORE'] if ENV.has_key?('GOOGLE_CREDENTIAL_STORE')
return well_known_path_for('credentials.yaml')
end
# Builds a path to a file in $HOME/.config/google (or %APPDATA%/google,
# on Windows)
def well_known_path_for(file)
if OS.windows?
File.join(ENV['APPDATA'], 'google', file)
else
File.join(ENV['HOME'], '.config', 'google', file)
end
end
# Returns application credentials for the given scope.
def application_credentials_for(scope)
Google::Auth.get_application_default(scope)
end
# Returns user credentials for the given scope. Requests authorization
# if requrired.
def user_credentials_for(scope)
FileUtils.mkdir_p(File.dirname(token_store_path))
if ENV['GOOGLE_CLIENT_ID']
client_id = Google::Auth::ClientId.new(ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'])
else
client_id = Google::Auth::ClientId.from_file(client_secrets_path)
end
token_store = Google::Auth::Stores::FileTokenStore.new(:file => token_store_path)
authorizer = Google::Auth::UserAuthorizer.new(client_id, scope, token_store)
user_id = options[:user] || 'default'
credentials = authorizer.get_credentials(user_id)
if credentials.nil?
url = authorizer.get_authorization_url(base_url: OOB_URI)
say "Open the following URL in your browser and authorize the application."
say url
code = ask "Enter the authorization code:"
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI)
end
credentials
end
# Gets the API key of the client
def api_key
ENV['GOOGLE_API_KEY'] || options[:api_key]
end
end
end

View File

@ -0,0 +1,62 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/analytics_v3'
require 'base_cli'
module Samples
# Examples for the Google Analytics APIs
#
# Sample usage session:
#
# $ ./google-api-samples analytics show_visits 55622900 --start='2015-12-01' --end='2015-12-08'
# ga:date ga:sessions ga:users ga:newUsers ga:percentNewSessions ga:sessionDuration ga:avgSessionDuration
# 20151201 0 0 0 0.0 0.0 0.0
# 20151202 0 0 0 0.0 0.0 0.0
# 20151203 1 1 1 100.0 0.0 0.0
# 20151204 2 2 1 50.0 616.0 308.0
# 20151205 0 0 0 0.0 0.0 0.0
# 20151206 1 1 1 100.0 0.0 0.0
# 20151207 0 0 0 0.0 0.0 0.0
# 20151208 2 2 1 50.0 0.0 0.0
#
class Analytics < BaseCli
Analytics = Google::Apis::AnalyticsV3
desc 'show_visits PROFILE_ID', 'Show visists for the given analytics profile ID'
method_option :start, type: :string, required: true
method_option :end, type: :string, required: true
def show_visits(profile_id)
analytics = Analytics::AnalyticsService.new
analytics.authorization = user_credentials_for(Analytics::AUTH_ANALYTICS)
dimensions = %w(ga:date)
metrics = %w(ga:sessions ga:users ga:newUsers ga:percentNewSessions
ga:sessionDuration ga:avgSessionDuration)
sort = %w(ga:date)
result = analytics.get_ga_data("ga:#{profile_id}",
options[:start],
options[:end],
metrics.join(','),
dimensions: dimensions.join(','),
sort: sort.join(','))
data = []
data.push(result.column_headers.map { |h| h.name })
data.push(*result.rows)
print_table(data)
end
end
end

View File

@ -0,0 +1,83 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/calendar_v3'
require 'base_cli'
module Samples
# Examples for the Google Calendar API
#
# Sample usage:
#
# $ ./google-api-samples calendar list --limit 10
class Calendar < BaseCli
Calendar = Google::Apis::CalendarV3
desc 'schedule', 'Create an event'
method_option :summary, type: :string, required: true
method_option :start, type: :string, required: true
method_option :end , type: :string, required: true
method_option :attendees, type: :array
def schedule
calendar = Calendar::CalendarService.new
calendar.authorization = user_credentials_for(Calendar::AUTH_CALENDAR)
event = {
summary: options[:summary],
attendees: Array(options[:attenddes]).map { |email| { email: email } },
start: {
date_time: DateTime.parse(options[:start])
},
end: {
date_time: DateTime.parse(options[:end])
}
}
event = calendar.insert_event('primary', event, send_notifications: true)
say "Created event '#{event.summary}' (#{event.id})"
end
desc 'list', 'List upcoming events'
method_option :limit, type: :numeric
def list()
calendar = Calendar::CalendarService.new
calendar.authorization = user_credentials_for(Calendar::AUTH_CALENDAR)
page_token = nil
limit = options[:limit] || 1000
now = Time.now.iso8601
begin
result = calendar.list_events('primary',
max_results: [limit, 100].min,
single_events: true,
order_by: 'startTime',
time_min: now,
page_token: page_token,
fields: 'items(id,summary,start),next_page_token')
result.items.each do |event|
time = event.start.date_time || event.start.date
say "#{time}, #{event.summary}"
end
limit -= result.items.length
if result.next_page_token
page_token = result.next_page_token
else
page_token = nil
end
end while !page_token.nil? && limit > 0
end
end
end

View File

@ -0,0 +1,82 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/drive_v3'
require 'base_cli'
module Samples
# Examples for the Google Drive API
#
# Sample usage:
#
# $ ./google-api-samples drive upload ~/myvideo.mov
class Drive < BaseCli
Drive = Google::Apis::DriveV3
desc 'upload FILE', 'Upload a file to Google Drive'
method_option :name, type: :string
def upload(file)
drive = Drive::DriveService.new
drive.authorization = user_credentials_for(Drive::AUTH_DRIVE)
metadata = {
name: options[:name] || file
}
result = drive.create_file(metadata, upload_source: file)
say "Upload complete"
end
desc 'download FILE_ID', 'Download a file from Google Drive'
method_option :out, type: :string
def download(file_id)
drive = Drive::DriveService.new
drive.authorization = user_credentials_for(Drive::AUTH_DRIVE)
dest = options[:out] || StringIO.new
drive.get_file(file_id, download_dest: dest)
if dest.is_a?(StringIO)
dest.rewind
STDOUT.write(dest.read)
else
say "File downloaded to #{options[:out]}"
end
end
desc 'list QUERY', 'Search for files'
method_option :limit, type: :numeric
def list(query)
drive = Drive::DriveService.new
drive.authorization = user_credentials_for(Drive::AUTH_DRIVE)
page_token = nil
limit = options[:limit] || 1000
begin
result = drive.list_files(q: query,
page_size: [limit, 100].min,
page_token: page_token,
fields: 'files(id,name),next_page_token')
result.files.each { |file| puts "#{file.id}, #{file.name}" }
limit -= result.files.length
if result.next_page_token
page_token = result.next_page_token
else
page_token = nil
end
end while !page_token.nil? && limit > 0
end
end
end

View File

@ -0,0 +1,114 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/pubsub_v1'
require 'base_cli'
module Samples
# Examples for the Google Cloud Pub/Sub API.
#
# Sample usage session:
#
# $ ./google-api-samples pubsub create_topic mytopic --project=623040240964
# # ./google-api-samples pubsub subscribe mysub --topic=mytopic --project=623040240964
# $ ./google-api-samples pubsub publish 'Hello!' --topic=mytopic --project=623040240964
# $ ./google-api-samples pubsub pull mysub --project=623040240964
# Received: Hello!
# $ ./google-api-samples pubsub unsubscribe mysub --project=623040240964
# $ ./google-api-samples pubsub delete_topic mytopic --project=623040240964
#
class PubSub < BaseCli
Pubsub = Google::Apis::PubsubV1
desc 'create_topic TOPIC_NAME', 'Create a topic'
method_option :project, type: :string, required: true
def create_topic(name)
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
topic = "projects/#{options[:project]}/topics/#{name}"
pubsub.create_topic(topic)
end
desc 'delete_topic TOPIC_NAME', 'Delete a topic'
method_option :project, type: :string, required: true
def delete_topic(name)
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
topic = "projects/#{options[:project]}/topics/#{name}"
pubsub.delete_topic(topic)
end
desc 'subscribe SUBSCRIPTION_NAME', 'Subscribe to a topic'
method_option :project, type: :string, required: true
method_option :topic, type: :string, required: true
def subscribe(name)
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
topic = "projects/#{options[:project]}/topics/#{options[:topic]}"
subscription = "projects/#{options[:project]}/subscriptions/#{name}"
pubsub.create_subscription(subscription, Pubsub::Subscription.new(topic: topic))
end
desc 'unsubscribe subscription_name', 'Ububscribe from a topic'
method_option :project, type: :string, required: true
def unsubscribe(name)
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
subscription = "projects/#{options[:project]}/subscriptions/#{name}"
pubsub.delete_subscription(subscription)
end
desc 'publish MESSAGE', 'Publish a message to a topic'
method_option :project, type: :string, required: true
method_option :topic, type: :string, required: true
def publish(message)
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
topic = "projects/#{options[:project]}/topics/#{options[:topic]}"
request = Pubsub::PublishRequest.new(messages: [])
request.messages << Pubsub::Message.new(data: message)
pubsub.publish_topic(topic, request)
end
desc 'pull SUBSCRIPTION_NAME', 'Pull message(s) from the topic'
method_option :project, type: :string, required: true
method_option :max, type: :numeric, default: 5
def pull(name)
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
subscription = "projects/#{options[:project]}/subscriptions/#{name}"
# Pull messages
response = pubsub.pull_subscription(subscription, Pubsub::PullRequest.new(max_messages: options[:max]))
response.received_messages.each do |received_message|
data = received_message.message.data
puts "Received: #{data}"
end
# Acknowledge receipt
ack_ids = response.received_messages.map{ |msg| msg.ack_id }
pubsub.acknowledge_subscription(subscription, Pubsub::AcknowledgeRequest.new(ack_ids: ack_ids))
end
end
end

View File

@ -0,0 +1,44 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/translate_v2'
require 'base_cli'
module Samples
# Examples for the Google Translate API
#
# Sample usage:
#
# $ ./google-api-samples translate 'Hola!' --target='en'
# Hello
#
class Translate < BaseCli
Translate = Google::Apis::TranslateV2
desc 'translate PHRASE', 'Translate a phrase'
method_option :source, type: :string
method_option :target, type: :string, required: true
def translate(phrase)
translate = Translate::TranslateService.new
translate.key = api_key
result = translate.list_translations(phrase, options[:target], source: options[:source])
puts result.translations.first.translated_text
end
default_task :translate
end
end

View File

@ -0,0 +1,44 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/youtube_v3'
require 'base_cli'
module Samples
# Examples for the YouTube APIs
#
# Sample usage:
#
# $ ./google-api-samples youtube upload ~/myvideo.mov --title="So funny!"
#
class YouTube < BaseCli
YT = Google::Apis::YoutubeV3
desc 'upload FILE', 'Upload a video to YouTube'
method_option :title, type: :string
def upload(file)
youtube = YT::YouTubeService.new
youtube.authorization = user_credentials_for(YT::AUTH_YOUTUBE)
metadata = {
snippet: {
title: options[:title] || file
}
}
result = youtube.insert_video('snippet', metadata, upload_source: file)
say "Upload complete"
end
end
end

View File

@ -1,51 +0,0 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'googleauth'
require 'google/apis/pubsub_v1'
Pubsub = Google::Apis::PubsubV1
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
project = ARGV[0] || 'YOUR_PROJECT_NAME'
topic = "projects/#{project}/topics/foo"
subscription = "projects/#{project}/subscriptions/bar"
# Create topic & subscription
pubsub.create_topic(topic)
pubsub.create_subscription(subscription, Pubsub::Subscription.new(topic: topic))
# Publish messages
request = Pubsub::PublishRequest.new(messages: [])
request.messages << Pubsub::Message.new(attributes: { "language" => "en" }, data: 'Hello')
request.messages << Pubsub::Message.new(attributes: { "language" => "en" }, data: 'World')
pubsub.publish_topic(topic, request)
# Pull messages
response = pubsub.pull_subscription(subscription, Pubsub::PullRequest.new(max_messages: 5))
response.received_messages.each do |received_message|
data = received_message.message.data
puts "Received #{data}"
end
# Acknowledge receipt
ack_ids = response.received_messages.map{ |msg| msg.ack_id }
pubsub.acknowledge_subscription(subscription, Pubsub::AcknowledgeRequest.new(ack_ids: ack_ids))
# Delete the subscription & topic
pubsub.delete_subscription(subscription)
pubsub.delete_topic(topic)

View File

@ -1,24 +0,0 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/translate_v2'
Translate = Google::Apis::TranslateV2
translate = Translate::TranslateService.new
translate.key = ARGV[0] || 'YOUR_API_KEY'
result = translate.list_translations(source: 'en', target: 'es', q: 'Hello world!')
puts result.translations.first.translated_text