본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Ruby용 AWS SDK (aws-sdk-s3)로 R2 사용하기

원문 보기 위키 갱신

Ruby용 aws-sdk-s3 젬으로 R2를 사용하는 예시예요. Gemfile에 의존성을 추가하고 S3 클라이언트로 버킷과 객체를 다루는 방법을 다뤄요.

출처: 문서

본문

많은 Ruby 프로젝트는 이런 자격 증명을 환경 변수에 저장하기도 해요.

Gemfile에 다음 의존성을 추가해요:

gem "aws-sdk-s3"

그러면 Ruby로 R2 버킷을 다룰 수 있어요:

require "aws-sdk-s3"

@r2 = Aws::S3::Client.new(
  # Retrieve your S3 API credentials for your R2 bucket via API tokens (see: https://developers.cloudflare.com/r2/api/tokens)
  access_key_id: "#{ACCESS_KEY_ID}",
  secret_access_key: "#{SECRET_ACCESS_KEY}",
  # Provide your Cloudflare account ID
  endpoint: "https://#{ACCOUNT_ID}.r2.cloudflarestorage.com",
  region: "auto", # Required by SDK but not used by R2
)

# List all buckets on your account
puts @r2.list_buckets

#=> {
#=>   :buckets => [{
#=>     :name => "your-bucket",
#=>     :creation_date => "…",
#=>   }],
#=>   :owner => {
#=>     :display_name => "…",
#=>     :id => "…"
#=>   }
#=> }

# List the first 20 items in a bucket
puts @r2.list_objects_v2(bucket: "your-bucket", max_keys: 20)

#=> {
#=>   :is_truncated => false,
#=>   :name => "your-bucket",
#=>   :prefix => nil,
#=>   :delimiter => nil,
#=>   :max_keys => 20,
#=>   :common_prefixes => [],
#=>   :encoding_type => nil,
#=>   :key_count => 3,
#=>   :contents => [
#=>     …,
#=>     …,
#=>     …,
#=>   ]
#=> }

더 알아보기 (Learn more)