访问已处理的ActiveStorage :: Variant的原始字节

时间:2018-12-29 00:14:15

标签: ruby-on-rails rails-activestorage

我正在尝试将variant of a file stored in Active Storage作为邮件的嵌入式附件。邮件的一面并不重要;我正在尝试读取上传图像的字节。

要包含原始上传的文件,此方法有效:

# 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}

但是,如果我想包括它的调整大小的变体而不是including the original file呢?

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

如何访问已处理图像的原始字节?

我当然仍然可以.download原件并进行自己的处理,但是希望可以有一种更简单的方法。谢谢!

1 个答案:

答案 0 :(得分:1)

回答我自己的问题,reading the code a little more,我可以这样做:

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

感觉应该有一种更优雅的方式吗?