Skip to main content

AWS SDK for Ruby (v3)

The AWS SDK for Ruby v3 is the modern modular Ruby SDK from AWS. The S3 service lives in the aws-sdk-s3 gem.

Install

gem install aws-sdk-s3

Or in your Gemfile:

gem 'aws-sdk-s3', '~> 1.150'

Initialize the client

filebase.rb
require 'aws-sdk-s3'

S3 = Aws::S3::Client.new(
endpoint: 'https://s3.filebase.io',
region: 'auto',
access_key_id: ENV.fetch('FILEBASE_KEY'),
secret_access_key: ENV.fetch('FILEBASE_SECRET'),
)

List buckets

S3.list_buckets.buckets.each do |bucket|
puts bucket.name
end

Create a bucket

S3.create_bucket(bucket: 'my-bucket')

# Public
S3.create_bucket(bucket: 'my-public-bucket', acl: 'public-read')

Upload an object

File.open('photo.jpg', 'rb') do |f|
S3.put_object(
bucket: 'my-bucket',
key: 'photo.jpg',
body: f,
content_type: 'image/jpeg',
cache_control: 'public, max-age=31536000',
)
end

For large files, use the resource API which switches to multipart automatically:

require 'aws-sdk-s3'

resource = Aws::S3::Resource.new(client: S3)
obj = resource.bucket('my-bucket').object('video.mp4')

obj.upload_file('./video.mp4',
content_type: 'video/mp4',
multipart_threshold: 8 * 1024 * 1024,
thread_count: 4,
)

List objects

S3.list_objects_v2(bucket: 'my-bucket', prefix: 'photos/').each do |response|
response.contents.each do |obj|
puts "#{obj.key} #{obj.size}"
end
end

The block-form pagination iterates pages automatically.

Download an object

S3.get_object(
response_target: './downloaded.jpg',
bucket: 'my-bucket',
key: 'photo.jpg',
)

# To memory
data = S3.get_object(bucket: 'my-bucket', key: 'photo.jpg').body.read

Delete an object

S3.delete_object(bucket: 'my-bucket', key: 'photo.jpg')

# Bulk
S3.delete_objects(
bucket: 'my-bucket',
delete: { objects: [{ key: 'a.jpg' }, { key: 'b.jpg' }] },
)

Pre-signed URLs

require 'aws-sdk-s3'

signer = Aws::S3::Presigner.new(client: S3)

# Read URL
url = signer.presigned_url(:get_object,
bucket: 'my-bucket',
key: 'private.pdf',
expires_in: 3600,
)

# Write URL
url = signer.presigned_url(:put_object,
bucket: 'uploads',
key: "user-#{user_id}/#{filename}",
content_type: 'image/jpeg',
expires_in: 600,
)

Resource API

resource = Aws::S3::Resource.new(client: S3)
bucket = resource.bucket('my-bucket')

bucket.objects(prefix: 'photos/').each do |obj|
puts "#{obj.key} #{obj.size}"
end

bucket.object('photo.jpg').upload_file('./photo.jpg')
bucket.object('photo.jpg').download_file('./downloaded.jpg')

Error handling

begin
S3.head_object(bucket: 'my-bucket', key: 'missing.jpg')
rescue Aws::S3::Errors::NotFound
# handle missing
rescue Aws::S3::Errors::ServiceError => e
warn "S3 error: #{e.code}: #{e.message}"
end

What's next