ruby-on-railsrails-activestoragevariant

Rails Active Storage: How to create "named variants" that are cropped by user-supplied coordinates


I have something like:

class User < ApplicationRecord

  has_one_attached :avatar do |attachable|
    attachable.variant :large,  resize_to_limit: [300, nil]
    attachable.variant :medium, resize_to_limit: [100, nil]
    attachable.variant :small,  resize_to_limit: [ 50, nil]
  end

end

How do I create...

Is it possible to "pass the coordinates to the model" somehow? If yes, how?

If not: Would the cropping need to happen separately in a controller action, creating a cropped version (of the original file), based upon which the "named variants" would be created? If so, how would that look?


Solution

  • This was added to Rails 7 (https://github.com/rails/rails/pull/39135):

    class User < ActiveRecord::Base
      has_one_attached :avatar, variants: {
        thumb: { resize: "100x100" },
        medium: { resize: "300x300", monochrome: true }
      }
    end
    
    class Gallery < ActiveRecord::Base
      has_many_attached :photos, variants: {
        thumb: { resize: "100x100" },
        medium: { resize: "300x300", monochrome: true }
      }
    end
    
    <%= image_tag user.avatar.variant(:thumb) %>