From 9900a21fd553dfc4c68d269a4e1baa4ada2cbf4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Tue, 27 Jul 2021 00:38:14 +0200 Subject: [PATCH] Use the `storage_` prefix for migrated attachments Just like we add the `storage_` prefix for new records so we can use both Active Storage and Paperclip at the same time. Now the migration actually works, at least for basic cases. --- lib/tasks/active_storage.rake | 4 +-- spec/lib/tasks/active_storage_spec.rb | 40 +++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 spec/lib/tasks/active_storage_spec.rb diff --git a/lib/tasks/active_storage.rake b/lib/tasks/active_storage.rake index 067957368..76ac1e5e5 100644 --- a/lib/tasks/active_storage.rake +++ b/lib/tasks/active_storage.rake @@ -46,7 +46,7 @@ namespace :active_storage do instance.send("#{attachment}_file_size"), Digest::MD5.base64digest(File.read(instance.send(attachment).path)), instance.updated_at.iso8601, - attachment, + "storage_#{attachment}", model.name, instance.id, instance.updated_at.iso8601 @@ -58,7 +58,7 @@ namespace :active_storage do ActiveStorage::Attachment.find_each do |attachment| dest = ActiveStorage::Blob.service.path_for(attachment.blob.key) - name = attachment.name + name = attachment.name.delete_prefix("storage_") source = attachment.record.send(name).path FileUtils.mkdir_p(File.dirname(dest)) diff --git a/spec/lib/tasks/active_storage_spec.rb b/spec/lib/tasks/active_storage_spec.rb new file mode 100644 index 000000000..f7150f41b --- /dev/null +++ b/spec/lib/tasks/active_storage_spec.rb @@ -0,0 +1,40 @@ +require "rails_helper" + +describe "active storage tasks" do + describe "migrate_from_paperclip" do + let(:run_rake_task) do + Rake::Task["active_storage:migrate_from_paperclip"].reenable + Rake.application.invoke_task("active_storage:migrate_from_paperclip") + end + + let(:storage_root) { ActiveStorage::Blob.service.root } + before { FileUtils.rm_rf storage_root } + + it "migrates records and attachments" do + document = create(:document, + attachment: nil, + paperclip_attachment: File.new("spec/fixtures/files/clippy.pdf")) + + expect(ActiveStorage::Attachment.count).to eq 0 + expect(ActiveStorage::Blob.count).to eq 0 + expect(test_storage_file_paths.count).to eq 0 + + run_rake_task + document.reload + + expect(ActiveStorage::Attachment.count).to eq 1 + expect(ActiveStorage::Blob.count).to eq 1 + expect(document.storage_attachment.filename).to eq "clippy.pdf" + expect(test_storage_file_paths.count).to eq 1 + expect(storage_file_path(document)).to eq test_storage_file_paths.first + end + + def test_storage_file_paths + Dir.glob("#{storage_root}/**/*").select { |file_or_folder| File.file?(file_or_folder) } + end + + def storage_file_path(record) + ActiveStorage::Blob.service.path_for(record.storage_attachment.blob.key) + end + end +end