Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bogdanRada/41b642c76dd8f8467246abb5697712fe to your computer and use it in GitHub Desktop.
Save bogdanRada/41b642c76dd8f8467246abb5697712fe to your computer and use it in GitHub Desktop.
Concern which duplicates attachments into ActiveStorage
module DuplicateActiveStorage
extend ActiveSupport::Concern
included do
after_commit do
duplicate_active_storage unless @is_migration
end
after_destroy :duplicate_active_storage
end
def duplicate_active_storage
picture_types = case self.class.name
when "Model1"
["picture", "avatar"]
when "Model2", "Model3"
["picture"]
when "Model4", "Model5"
["image"]
else
["logo"]
end
transfer_to_active_storage(picture_types)
end
private
def transfer_to_active_storage(picture_types)
picture_types.each do |picture_type|
next unless send("saved_change_to_#{picture_type}_updated_at?") ^ @is_migration
next unless send(picture_type.to_s).exists?
if try(:deleted?) || destroyed?
remove_active_storage
next
end
ActiveRecord::Base.transaction do
blob = ActiveStorage::Blob.create_after_upload!(
io: open(URI.parse(URI.escape("https://s3-#{ENV['AWS_REGION']}.amazonaws.com/#{ENV['AWS_BUCKET']}/" + key(picture_type.to_s)))),
filename: send("#{picture_type}_file_name"),
content_type: send("#{picture_type}_content_type")
)
blob.attachments.create(
name: picture_type.to_s,
record_type: self.class.name,
record_id: id
)
end
clear_attribute_changes(["#{picture_type}_updated_at"])
end
end
def key(attachment)
filename = send("#{attachment}_file_name")
fingerprint = send("#{attachment}_fingerprint")
klass = self.class.table_name
id = self.id
id_partition = ("%09d".freeze % id).scan(/\d{3}/).join("/".freeze)
"#{klass}/#{attachment.pluralize}/#{id_partition}/original/#{fingerprint}#{filename}"
end
def remove_active_storage
ActiveStorage::Attachment.find_by(record_type: self.class.name, record_id: id)&.purge
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment