适用于 Ruby 的 Amazon SDK 的 Hello 教程 - Amazon 适用于 Ruby 的 SDK
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

适用于 Ruby 的 Amazon SDK 的 Hello 教程

使用适用于 Ruby 的 S Amazon DK 向亚马逊 S3 打个招呼。以下示例显示了 Amazon S3 存储桶的列表。

编写代码

复制并在新的源文件中粘贴以下代码。将文件命名为 hello-s3.rb

require 'aws-sdk-s3' # Wraps Amazon S3 resource actions. class BucketListWrapper attr_reader :s3_resource # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource. def initialize(s3_resource) @s3_resource = s3_resource end # Lists buckets for the current account. # # @param count [Integer] The maximum number of buckets to list. def list_buckets(count) puts 'Found these buckets:' @s3_resource.buckets.each do |bucket| puts "\t#{bucket.name}" count -= 1 break if count.zero? end true rescue Aws::Errors::ServiceError => e puts "Couldn't list buckets. Here's why: #{e.message}" false end end # Example usage: def run_demo wrapper = BucketListWrapper.new(Aws::S3::Resource.new) wrapper.list_buckets(25) end run_demo if $PROGRAM_NAME == __FILE__

Amazon 适用于 Ruby 的 SDK 采用模块化设计,并采用以下方式分隔 Amazon Web Services 服务。安装 Gem 后,Ruby 源文件顶部的 require 语句会导入 Amazon S3 服务的 Amazon SDK 类和方法。有关可用 Amazon 服务 gem 的完整列表,请参阅 Amazon SDK for Ruby README 文件的 “支持的服务” 表。

require 'aws-sdk-s3'

运行程序

打开命令提示符以运行 Ruby 程序。用于运行 Ruby 程序的典型命令语法是:

ruby [source filename] [arguments...]

此示例代码不使用任何参数。要运行此代码,请在命令提示符下输入以下内容:

$ ruby hello-s3.rb

Windows 用户的注意事项

在 Windows 上使用 SSL 证书并运行 Ruby 代码时,您可能会看到类似如下的错误。

C:\Ruby>ruby buckets.rb C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `connect': SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (Seahorse::Client::NetworkingError) from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `block in connect' from C:/Ruby200-x64/lib/ruby/2.0.0/timeout.rb:66:in `timeout' from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `connect' from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:862:in `do_start' from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:857:in `start' ...

要修复此问题,请在第一次 Amazon 调用之前将以下行添加到 Ruby 源文件中。

Aws.use_bundled_cert!

如果您在 Ruby 程序中只使用 aws-sdk-s3 Gem,并且想要使用捆绑证书,则还需要添加 aws-sdk-core Gem。

后续步骤

要测试许多其他 Amazon S3 操作,请查看上的 “Amazon 代码示例存储库” GitHub。