Last active
August 8, 2024 21:01
-
-
Save jeremysmithco/df6707af3822bb0df7400718d4b76b65 to your computer and use it in GitHub Desktop.
Rough sketch of Active Storage calculated variants
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
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 |
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 '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 |
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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Part of discussion here: https://x.com/jeremysmithco/status/1821642513356300514