Created
April 21, 2022 10:41
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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