你好教程為 AWS SDK for Ruby - AWS SDK for Ruby

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

你好教程為 AWS SDK for Ruby

使用 AWS SDK for Ruby 向 Amazon 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__

AWSSDK for Ruby 被設計為模塊化,並且由AWS 服務. 安裝 gem 之後,Ruby 來源檔案頂端的require陳述式會匯入 Amazon S3 服務的 AWS SDK 類別和方法。如需可用AWS服務 gem 的完整清單,請參閱 Ruby 讀我檔案 AWS SDK 的支援服務表格。

require 'aws-sdk-s3'

執行程式

打開命令提示符來運行你的 Ruby 程序。運行 Ruby 程序的典型命令語法是:

ruby [source filename] [arguments...]

此範例程式碼不使用任何引數。若要執行此程式碼,請在命令提示字元中輸入下列命令:

$ ruby hello-s3.rb

視窗使用者注意事項

當您在 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' ...

若要修正此問題,請在第一次AWS呼叫之前,將下列行新增至 Ruby 原始碼檔案。

Aws.use_bundled_cert!

如果您只在 Ruby 程序中使用 aws-sdk-s3 gem 並且想要使用捆綁的證書,則還需要添加 aws-sdk-core gem。

後續步驟

若要測試許多其他 Amazon S3 操作,請查看上的AWS程式碼範例儲存庫 GitHub。