Skip to content

Instantly share code, notes, and snippets.

@tsubik
Last active July 19, 2019 11:05
Show Gist options
  • Save tsubik/25554e9e13dd550963a3d848da166dc3 to your computer and use it in GitHub Desktop.
Save tsubik/25554e9e13dd550963a3d848da166dc3 to your computer and use it in GitHub Desktop.
# Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
amazon:
service: S3Extended
access_key_id: <%= ENV.fetch('AWS_ACCESS_KEY_ID') {} %>
secret_access_key: <%= ENV.fetch('AWS_SECRET_ACCESS_KEY') {} %>
region: <%= ENV.fetch('AWS_REGION') %>
bucket: <%= ENV.fetch('S3_BUCKET_NAME') %>
root: <%= ENV['S3_FILES_PREFIX'] %>
cdn_url: <%= ENV['CLOUDFRONT_URL'] %>
upload:
acl: 'public-read'
require 'active_storage/service/s3_service'
class ActiveStorage::Service::S3ExtendedService < ActiveStorage::Service::S3Service
attr_reader :root, :cdn_url
def initialize(bucket:, upload: {}, **options)
@root = options.delete(:root)
@cdn_url = options.delete(:cdn_url)
super(bucket: bucket, upload: upload, **options)
end
def url(key, **)
return super unless cdn_url
"#{cdn_url}/#{path_for(key)}"
end
def delete_prefixed(prefix)
super(path_for(prefix))
end
# TODO: not needed with Rails 6
def upload(key, io, checksum: nil, content_type: nil, **)
instrument :upload, key: key, checksum: checksum do
object_for(key).put(upload_options.merge(body: io, content_md5: checksum, content_type: content_type))
rescue Aws::S3::Errors::BadDigest
raise ActiveStorage::IntegrityError
end
end
private
def object_for(key)
path = path_for(key)
bucket.object(path)
end
def path_for(key)
root.present? ? File.join(root, key) : key
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment