Skip to content

Instantly share code, notes, and snippets.

@ashikajith
Created September 22, 2022 21:54
Show Gist options
  • Save ashikajith/cbf9f639e4cdf323260c4d28394c1ce4 to your computer and use it in GitHub Desktop.
Save ashikajith/cbf9f639e4cdf323260c4d28394c1ce4 to your computer and use it in GitHub Desktop.
Carrier wave to Active Storage Syncing
#app/models/profile.rb
def sync_active_storage_future_logo
# Abort if the attachment is default
return unless logo.present? && (logo.id != DefaultAvatar.for_logo.asset_id)
future_logo.purge if future_logo.attached? # remove the existing image from new attachment field
sync_future_logo
end
def sync_future_logo # rubocop:disable Metrics/AbcSize
file_attachment = logo.attachment
return if file_attachment.file&.file.nil?
presigned_url = file_attachment.file.file.presigned_url(:get, expires_in: 3600)
temp_file = Tempfile.new("model_logo", "tmp/", binmode: true)
begin
URI.parse(presigned_url).open do |file|
temp_file.write(file.read)
end
temp_file.rewind # move the file cursor to the beginning
future_logo.attach(
io: temp_file,
content_type: file_attachment.content_type,
filename: file_attachment.file.filename
)
rescue OpenURI::HTTPError => e
Rails.logger.info(message: "Missin logo image #{id} Error: #{e}")
end
end
# rake task
task process_migration_in_job_domain_post: :environment do
Post.in_batches do |posts|
Post.transaction do
posts.each do |post|
Rails.logger.info(message: "Processing migration for Post #{post.id}")
post.sync_active_storage_future_logo
Rails.logger.info(message: "Migration Completed for Post #{post.id}")
end
sleep(0.01)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment