How to use carrierwave's from_version to reference the processed base image, rather than the unprocessed one

Viewed 141

I am working on a site which needs to have a newsletter page, with thumbnails. The PDFs are stored on a different site, but that site does not have thumbnails, so I must generate them myself and link the thumbnail to that site.

I cannot store the original PDF — the linked version is canonical, and having out-of-date cached versions is unacceptable. The additional storage usage might also cause an extra monthly expense for the non-profit organisation the site is for, so I do not want to leave these lying around when they're not needed.

I have the following code:

class DocumentUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick
  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def content_type_whitelist
    'application/pdf'
  end

  def full_filename(for_file)
    parent_name = super(for_file)
    return unless parent_name
    extension = '.pdf'
    base_name = parent_name.chomp(extension)
    if version_name
      base_name = base_name[version_name.size.succ..-1]
    end
    [base_name, version_name].compact.join("_") + '.png'
  end

  # Process files as they are uploaded:
  process convert_pdf_front: [500, 500]

  version :medium do
    process convert_pdf_front: [160, 160]
  end

  version :small do
    process convert_pdf_front: [80, 80]
  end

  private

  def convert_pdf_front(width, height)
    manipulate! do |img|
      img.format('png') do |c|
        c.resize "#{width}x#{height}"
      end
      img
    end
  end
end

This works as expected, but the medium and small versions are converted from the original PDF, making for a rather slow process.

If I replace the processing code with this:

  version :full do
    process convert_pdf_front: [500, 500]
  end

  version :medium, from_version: :full do
    process convert: 'png'
    process resize_to_fit: [160, 160]
  end

  version :small, from_version: :full do
    process convert: 'png'
    process resize_to_fit: [80, 80]
  end

then the medium and small versions are converted from the full version, but the original PDF is left lying around.

Is there a way to use from_version to do the conversion from the converted original document — that is, from the 500x500 PNG rather than the PDF — that doesn't leave the original PDF cluttering the place up? Is there a special version name that points to the original document after it's gone through any process commands, rather than before?

(I would rather not simply have a reaper process nuke the PDFs later, as Carrierwave regards those as the originals. I'd like Carrierwave to treat the 500x500 PNG as the original in all cases and never store the PDF once it's done with the conversion process.)

0 Answers
Related