Skip to content

Instantly share code, notes, and snippets.

@jeremysmithco
Last active August 8, 2024 21:01
Show Gist options
  • Save jeremysmithco/df6707af3822bb0df7400718d4b76b65 to your computer and use it in GitHub Desktop.
Save jeremysmithco/df6707af3822bb0df7400718d4b76b65 to your computer and use it in GitHub Desktop.
Rough sketch of Active Storage calculated variants
Rails.application.config.to_prepare do
ActiveStorage::Attachment.class_eval do
private
def transform_variants_later
if record.respond_to?(:calculated_variants)
record.calculated_variants[name.to_sym]&.values.each do |transformations|
blob.preprocessed(transformations)
end
end
named_variants.each do |_name, named_variant|
blob.preprocessed(named_variant.transformations) if named_variant.preprocessed?(record)
end
end
end
end
require 'image_processing'
module ImageProcessing::Vips::CustomProcessing
extend ActiveSupport::Concern
included do
def lighten(percentage)
overlay = image.new_from_image([255, 255, 255, (255 * percentage).to_i])
image.composite(overlay, :over)
end
end
end
class Document < ApplicationRecord
has_one_attached :watermark
after_save_commit :transform_watermark_print_variant_later, if: ->(document) { document.watermark_opacity_previously_changed? }
def calculated_variants
{
watermark: {
print: { resize_to_limit: [1_000, 1_000], lighten: lighten_value }
}
}
end
def lighten_value
return 0 if watermark_opacity < 0
[watermark_opacity.to_f / 100.0, 1].min
end
def transform_watermark_print_variant_later
ActiveStorage::TransformJob.perform_later(watermark.blob, calculated_variants.dig(:watermark, :print))
end
end
@jeremysmithco
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment