Add a rake task to move user avatars to Active Storage
authorTom Hughes <tom@compton.nu>
Mon, 15 Jul 2019 16:29:39 +0000 (17:29 +0100)
committerTom Hughes <tom@compton.nu>
Mon, 15 Jul 2019 18:09:50 +0000 (19:09 +0100)
lib/tasks/upgrade_avatars.rake [new file with mode: 0644]

diff --git a/lib/tasks/upgrade_avatars.rake b/lib/tasks/upgrade_avatars.rake
new file mode 100644 (file)
index 0000000..03939da
--- /dev/null
@@ -0,0 +1,15 @@
+namespace "storage" do
+  task :upgrade_avatars => :environment do
+    User.active.where.not(:image_file_name => nil).in_batches.each_record do |user|
+      io = File.open(user.image.path)
+      filename = user.image.original_filename
+      content_type = if user.image.content_type.nil?
+                       MimeMagic.by_magic(io)&.type
+                     else
+                       user.image.content_type
+                     end
+
+      user.avatar.attach(:io => io, :filename => filename, :content_type => content_type)
+    end
+  end
+end