Accessing the raw bytes of a processed ActiveStorage::Variant

Viewed 619

I'm trying to include a variant of a file stored in Active Storage as an inline attachment for a mailer. The mailer side of things isn't important; I'm trying to read the bytes of an uploaded image.

To include the original uploaded file, this works:

# The model
class Newsletter < ApplicationRecord
  has_one_attached :header
end

# The mailer
class NewsletterMailer < ApplicationMailer
  def mailshot
    @newsletter = params[:newsletter]
    if @newsletter.header.attached?
      attachments.inline['header'] = @newsletter.header.download
    end
  end
end

# In the view (MJML HAML, but you get the idea...)
- if attachments['header'].present?
  %mj-image{src: attachments['header'].url}

But what if instead of including the original file, I want to include a resized variant of it?

attachments.inline['header'] =
  @newsletter
    .header
    .variant(resize: '100x100')
    .processed
    .???

How do I access the raw bytes of the processed image?

I can of course still .download the original and do my own processing, but rather hoping there might be an easier way. Thanks!

1 Answers

Answering my own question, and reading the code a little more, I can do it like this:

if @newsletter.header.attached?
  processed = @newsletter.header.variant(resize: '100x100').processed
  attachments.inline['header'] = processed.service.download processed.key
end

It feels like there should be a more elegant way?

Related