Search code examples
ruby-on-railscarrierwavejcrop

Carrierwave and Jcrop, delete original after crop?


I'm having a difficult time getting Carrierwave to delete the original file after the cropped versions are made. I'm making a 600 pixel version of the upload for the user to crop but after the crop I want that version to get deleted since it's never used on the site.

I've tried several solutions found online but they all delete the large version before the crop, not after.

Here is my Carrierwave uploader:

# encoding: utf-8

class AvatarUploader < CarrierWave::Uploader::Base

  include CarrierWave::RMagick

  storage :file
  # storage :fog

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

  # Only allows jpg, jpeg, or png
  def extension_white_list
    %w(jpg jpeg png)
  end

  resize_to_limit(600, 600)

  version :profile do
    process :crop
    resize_to_fill(120, 120)
    def full_filename (for_file = model.file) 
      "profile.png" 
    end
  end

  version :timeline do
    process :crop
    resize_to_fill(50, 50)
    def full_filename (for_file = model.file) 
      "timeline.png" 
    end
  end

  version :navigation do
    process :crop
    resize_to_fill(20, 20)
    def full_filename (for_file = model.file) 
      "navigation.png" 
    end
  end

  def crop
    if model.crop_x.present?
      resize_to_limit(600, 600)
      manipulate! do |img|
        x = model.crop_x.to_i
        y = model.crop_y.to_i
        w = model.crop_w.to_i
        h = model.crop_h.to_i
        img.crop!(x, y, w, h)
      end
    end
  end

end

Solution

  • You could either use an after_store callback to remove the original file (using File.delete) or you could modify the original so that it's the largest size you need:

    version :normal do
       process :resize_to_limit => [600,600]
    end