Rake task for migrating from ActiveStorage to Shrine

Viewed 178

I've got a Rails 5.2 application using ActiveStorage and S3 but I've been having intermittent timeout issues. I'm also just a bit more comfortable with shrine from another app.

I've been trying to create a rake task to just loop through all the records with ActiveStorage attachments and reupload them as Shrine attachments, but I've been having a few issues.

I've tried to do it through URL and through tempfiles, but I'm not exactly sure of the right steps to fetch the activestorage version and to get it uploaded to S3 and saved on the record as a shrine attachment.

I've tried the rake task here, but I think the method is only available on rails 6.

Any tips or suggestions?

1 Answers

I'm sure it's not the most efficient, but it worked.

task :listing_images => :environment do
  listings = Listing.all

  listings.each do |listing|
    if listing.exterior.attached?
      # fetch file and save to tempfile
      tempfile = Tempfile.new([listing.exterior.filename.base.to_s, listing.exterior.filename.extension_with_delimiter.to_s], Rails.root.join('tmp'))
      tempfile.binmode
      listing.exterior.send(:download_blob_to, tempfile)
        
      # upload to S3 through shrine and save on column
      uploader = ImageUploader.new(:store)
      uploaded_file = uploader.upload(File.open(tempfile.path))
      listing.update_columns(exterior_image_data: uploaded_file.to_json)

      # generate different image sizes
      generate_derivatives(listing.reload, view)
          
      tempfile.close!
    end
  end
end
Related