Websites/app/logical/storage_manager/s3.rb

48 lines
1.0 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
module StorageManager
class S3
attr_reader :base_url
def initialize(endpoint:, access_key_id:, secret_access_key:, bucket:, base_url:)
@s3 = Aws::S3::Resource.new(
region: "weur",
endpoint: endpoint,
credentials: Aws::Credentials.new(access_key_id, secret_access_key),
).bucket(bucket)
@base_url = base_url
end
def delete(path)
return unless exists?(path)
@s3.object(trim(path)).delete
end
def exists?(path)
@s3.object(trim(path)).exists?
end
def get(path)
@s3.object(trim(path)).get.body
end
def put(path, io)
@s3.object(trim(path)).put(body: io, content_type: Marcel::MimeType.for(io))
end
def upload(path, body)
put(path, body)
"#{base_url}#{path}"
end
def url_for(entry)
"#{base_url}#{entry.path}"
end
def trim(path)
# R2 for some reason doesn't trim preceding slashes
path.sub(%r{^/}, "")
end
end
end