[Feature Proposal][PR attached] Allow devs to define default transformations for Image Blobs

Right now if a developer wants to ensure that all images in their app are optimized, they need to create a helper on top of the image_helper and ensure during code reviews that this helper is being used. We can improve this by plugging into an already existing feature of Active Storage: converting image blobs that are not considered web images, but are variable, into PNGs.

My proposal is to follow analyers and previewer and add optimizers. Then we change default_variant_transformations method in representable to call those optimizers instead of simply returning the format that should be used for the image blob.

Before:

def default_variant_transformations
  { format: default_variant_format }
end

What it would look like

def default_variant_transformations
  optimizer_class.new(self).transformations
end

def optimizer_class
  ActiveStorage.optimizers.detect { |klass| klass.accept?(format) }
end

Each optimizer would be responsible to handle a single image format, with a default optimizer that would inherit the existing code. If we define good defaults for JPEG, PNG and WEBP, we can save developers the need to understand how to optimize their images (conceptual compression).

As an extra, if the representations_controller can detect and parse the accept header, the optimizer would also be able to serve WebP instead of JPEG or PNG for browsers that support it.

I’ve prepared a PR for this, to help discussion.

1 Like

This PR has been closed. A new PR based on the feedback I’ve received is open at Make active storage default transformations configurable by brenogazzola · Pull Request #42936 · rails/rails · GitHub