Rails makes ActiveStorage `web_image_content_types` configurable

Rails added config.active_storage.web_image_content_types option to ActiveStorage which allows application to make content types configurable.

Before

The image variants were defined in ActiveStorage::Variant class as below.

WEB_IMAGE_CONTENT_TYPES = %w[ image/png image/jpeg image/jpg image/gif ]

WEB_IMAGE_CONTENT_TYPES constant was used in the Rails code for identifying and processing the image variant.

And if the image content-type is different from the above constant, it would fallback to default PNG format.

After

We can now add the image variants in our configuration file with this ActiveStorage update, as below

config.active_storage.web_image_content_types = %w(image/jpeg image/png image/webp image/jpg)

The above config accepts an array of strings, which are image content types. The image variants will be processed in the above given type. If no value is set to the config Rails uses the default image content-type

%w(image/png image/jpeg image/jpg image/gif)

Let’s say, we have a User model with avatar as one of the columns for storing user profile picture.

class User < ApplicationRecord
  has_one_attached :avatar
end

We can attach a webp image format as below

user = User.new(email: "[email protected]")

user.avatar.attach(io: File.open("/path/to/image.webp"), filename: "image.webp", content_type: "image/webp")

user.save!

Need help on your Ruby on Rails or React project?

Join Our Newsletter