How to set content-encoding metadata when uploading a file with ActiveStorage?

I’m working on a landing pages provider, and some of the files we serve are stylesheets and javascripts tailored per landing page.

We use ActiveStorage to store those assets and cache them with Cloudfront to serve them to users.

One of the suggestions from Lighthouse is to serve these assets gzipped. It’s fairly simple to compress the assets using ActiveSupport::Gzip but it’s not that simple to set the content encoding.

Among the response headers, browsers need to receive:

content-encoding: gzip;
content-type: text/css;

But unless I monkey patch the blob model and services, I can’t find a way to set the content encoding easily.

Do you have any suggestions on how to approach this?


I did some research and found out that if I pass a hash to the attach method then I can:

  1. Include the content_encoding I want to use
  2. Include the content_type I want to use
  3. Add identify: false to avoid ActiveStorage setting the content type
  4. Override the build_after_unfurling method to include the content_encoding as an argument https://github.com/rails/rails/blob/6-1-stable/activestorage/app/models/active_storage/blob.rb#L89
  5. Lastly, override the upload method of the service I’m using to receive the content_encoding and pass it to the underlying service (i.e. aws s3 sdk) https://github.com/rails/rails/blob/6-1-stable/activestorage/lib/active_storage/service/s3_service.rb#L26

Does this make sense? I’m not suggesting to make this change in Rails, I’m just seeking advice on whether this is a good idea to do on my project or not.