[ActiveStorage] Pre-defined Variants

Hello all -

Firstly, huge thanks to those who have worked on ActiveStorage so far. The library seems to be coming along nicely.

ActiveStorage currently allows you to define variants of an attachment as follows:

class User < ActiveRecord::Base
  has_one_attached :avatar

  # ...

user.avatar.variant(resize: "100x100>")
user.avatar.variant(resize: "100x100>", caption: "foo")
user.avatar.variant(resize: "200x200", rotate: "-90")

I’d like to propose the following functionality that lets users configure and pre-define variants.

class User < ActiveRecord::Base
    variants: {
      small: { resize: "100x100>" }
      small_captioned: { resize: "100x100>", caption: "foo" }
      medium_rotated: { resize: "200x200", rotate: "-90" }

  # ...


# Something not pre-definied
user.avatar.variant(rotate: "120")

This is similar in concept to how existing attachment libraries (paperclip, carrierwave, etc…) have allowed definition and configuration of variants.

It is true that this functionality can be mimicked outside of activestorage by having the developer maintain a manual mapping of key names to variant configurations. However, I believe this should be part of ActiveStorage directly because -

  1. It leads to cleaner/more readable code (e.g. user.avatar.variant(:small) is easy to understand)
  2. It keeps configuration consolidated inline with has_one_attached, which is similar to how options are already defined inline with has_one, has_many, etc…
  3. It’s fully backward compatible with how variants are invoked right now and doesn’t force you to use a particular approach.

Would such a feature be accepted if I were to submit a pull request for it?

Thank you!

I do remember proposing this at one point internally:

has_one_attached :avatar do |attachable|
attachable.variant :small, resize: ’100x100>’


I’m also fine with exposing it as variant(:small) or for one offs variant(:small, caption: ’foo’).

I’m not looking to see this through though, so you’d have to get George Claghorn or someone else on board for this ride.

Appreciate the extensive write up with reasoning!

@kasper - Allowing the one-off options on a given variant is an even better approach and just as easily implementable. Thanks for the suggestion.

I’m not looking to see this through though, so you’d have to get George Claghorn or someone else on board for this ride.

Totally understood :slight_smile:

@George - would love to hear your thoughts on this. If you agree, I don’t mind picking up the development and submitting a patch.


Please do open a PR!