Skip to content

Instantly share code, notes, and snippets.

@owen2345
Created April 21, 2022 10:41
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 owen2345/2d5db0238a5dbd76951fdb7261dc97f7 to your computer and use it in GitHub Desktop.
Save owen2345/2d5db0238a5dbd76951fdb7261dc97f7 to your computer and use it in GitHub Desktop.
Rails Activestorage apply variant before uploading. Crop image before uploading. Process image before uploading.
# config/initializers/activestorage.rb
# Ability to auto apply :default variant (if defined) before uploading original image
Rails.application.config.after_initialize do
ActiveStorage::Blob.class_eval do
alias_method :upload_without_unfurling_orig, :upload_without_unfurling
def upload_without_unfurling(io)
variant = attachments.first.send(:variants)
default_variant = variant[:default]
if default_variant
ActiveStorage::Variation.wrap(default_variant).transform(io) do |output|
unfurl output, identify: identify
upload_without_unfurling_orig(output)
end
else
upload_without_unfurling_orig(io)
end
end
end
end
class User < ApplicationRecord
has_one_attached :photo do |attachable|
attachable.variant :thumb, resize_to_fill: [100, nil]
# This variant will be applied before uploading the original image
attachable.variant :default, strip: true, quality: 70, resize_to_fill: [500, 500]
end
end
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'when uploading photo' do
it 'applies :default variant before uploading the original image' do
allow(ActiveStorage::Variation).to receive(:wrap).and_call_original
create(:user, :with_photo)
exp_args = hash_including(resize_to_fill: [500, 500])
expect(ActiveStorage::Variation).to have_received(:wrap).with(exp_args)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment