Skip to content

Instantly share code, notes, and snippets.

@palkan palkan/patch.rb Secret
Last active May 25, 2019

Embed
What would you like to do?
Active Storage transformations
# frozen_string_literal: true
# Active Storage patch for application wide transformations
# The main purpose of the code below is DRY.
# We don't want to repeat everywhere `User.avatar.variant(many_transformation_options)`.
# Instead of this we simply write `User.avatar.variant(:medium)`
# And if one day when we decide to change any size of variants, then we change it in one place.
#
# Waiting for https://github.com/rails/rails/pull/35290
ActiveStorage.extend(Module.new do
def transformations
return @transformations if defined?(@transformations)
files = [
Rails.root.join("config", "transformations.yml"),
# fallback to default config
Pathname.new(File.join(__dir__, "transformations.yml"))
]
file = files.detect(&:exist?)
@transformations = YAML.load_file(file).deep_symbolize_keys!
raise ArgumentError, "Variant called :medium is missing in #{file}" unless
@transformations.key?(:medium)
@transformations
end
end)
# Original source at https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/transformers/transformer.rb
ActiveStorage::Transformers::Transformer.prepend(Module.new do
def transformations
ActiveStorage.transformations.fetch(@transformations) { super }
end
end)
# "Fix" this change https://github.com/rails/rails/commit/6be1446fc7f4b159097533562920662b85155113
ActiveSupport.on_load(:active_storage_blob) do
ActiveStorage::Variation.prepend(Module.new do
def initialize(transformations)
return @transformations = transformations if transformations.is_a?(Symbol)
super
end
end)
end
# See more options at https://github.com/janko/image_processing/blob/master/doc/vips.md#readme
thumb:
convert: jpg
resize_to_fill: [64, 64]
small:
convert: jpg
resize_to_fill: [128, 128]
medium:
convert: jpg
resize_to_fill: [200, 200]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.