I have migrated my Rails app to 5.2.0. Before I was using Paperclip. Paperclip generates different variants like thumbnail and avatar when an image is uploaded. How can I achieve this with ActiveStorage? I know we can do this user.avatar.variant(resize_to_fit: [100, 100]) but to me it's like doing this over and over again. I'm aiming to do pre-processing of these variants once it's uploaded.
Also you guys can suggest a better technique if this is bad from your experience.
Using .processed is the correct way to check if that variant was already processed and uploaded to the storage service.
One thing that Paperclip did nicely was the styles: {} object, in which you could list all the different transformations you wanted to do for thumbnails, etc, and name them.
Here's how I am handling named & stored transformations. This also keeps my template syntax shorter:
class Image < ActiveRecord::Base
  has_one_attached :image_file
  def self.sizes
    {
      thumbnail: { resize: "100x100" },
      hero1:     { resize: "1000x500" }
    }
  end
  def sized(size)
    self.image_file.variant(Image.sizes[size]).processed
  end
end
Then in a template, say I have @image, I can simply call @image.sized(:hero1)
@aguardientico is correct that by add the .processed method to your variant object which will use the blob key to check if the file already exists on your service before attempting to re-produce the whole process again.
Also something to know in addition is the resize_to_fit is a ImageProcessing gem transformation method and is not supported yet by Rails 5.2. Instead right now it uses MiniMagick where you would append > to the resize method for paperclip.
so rewritten it would look like user.avatar.variant(resize: "100x100>")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With