Skip to content

Instantly share code, notes, and snippets.

@ruanltbg
Created March 16, 2024 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruanltbg/4256bd19e27a374dde9dccedd9b60793 to your computer and use it in GitHub Desktop.
Save ruanltbg/4256bd19e27a374dde9dccedd9b60793 to your computer and use it in GitHub Desktop.
Migrate refile files to active storage
require 'mini_magick' # included by the image_processing gem
require 'aws-sdk-s3' # included by the aws-sdk-s3 gem
class MigrateRefileToActiveStorage
attr_accessor :model, :attribute
def initialize(model, attribute)
@model = model
@attribute = attribute
end
def run
puts "Migrating #{@mode} #{@attribute} file from Refile to ActiveStorage"
@model.constantize.where.not(:"#{@attribute}_id" => nil).find_each do |instance|
next if instance.send(@attribute).attached?
id = file_id(instance.send("#{@attribute}_id"))
next unless Easymovie::Aws.bucket.object(id).exists?
tmp_file = Tempfile.new
# Download the S3 file to our temp file
Easymovie::Aws.s3.client.get_object(
response_target: tmp_file.path,
bucket: Easymovie::Aws.bucket.name,
key: id
)
# Find content_type of S3 file using ImageMagick
# Verify if the model has the content_type column otherwise infers using MiniMagick
content_type = instance.try(:"#{@attribute}_content_type") || MiniMagick::Image.new(tmp_file.path).mime_type
# Attach tmp file to our User as an ActiveStorage attachment
filename = instance.try(:"#{@attribute}_filename") || "file.#{content_type.split('/').last}"
instance.send(@attribute).attach(
io: tmp_file,
filename: filename,
content_type: content_type
)
if instance.send(@attribute).attached?
instance.save # Save our changes to the instance
puts "- migrated #{@mode} #{@attribute}'s file for instance ##{instance.id}."
else
puts "- \e[31mFailed to migrate the file for #{@model} instance ##{instance.id} with Refile id #{instance.send("#{@attribute}_id")}\e[0m"
end
tmp_file.close
end
end
private
def file_id(id)
return id if id.match('store/')
"store/#{id}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment