ruby-on-railscarrierwavefog

Carrierwave: Move version name to end of filename, instead of front


Currently with Carrierwave, after uploading a file like foo.png when creating different versions like so:

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  storage :fog
  def store_dir
    "#{model.class.to_s.underscore}/#{model.id}"
  end

  version :thumb do
    process :resize_to_fit => [500, 500]
  end
end

that results in the files being uploaded as:

thumb_foo.png
foo.png

I want to move "thumb" to the end of the filename for SEO reasons. Based on their docs here I added:

  def full_filename(for_file)
    if parent_name = super(for_file)
      extension = File.extname(parent_name)
      base_name = parent_name.chomp(extension)
      [base_name, version_name].compact.join("_") + extension
    end
  end

  def full_original_filename
    parent_name = super
    extension = File.extname(parent_name)
    base_name = parent_name.chomp(extension)
    [base_name, version_name].compact.join("_") + extension
  end

The docs say this should result in:

foo_thumb.png
foo.png

However, I end up actually getting the following:

thumb_foo_thumb.png
foo.png

Any idea what I'm doing wrong?


Solution

  • Simply use #full_filename under the version block:

    class AvatarUploaer < CarrierWave::Uploader::Base
      include CarrierWave::MiniMagick
    
      storage :file
    
      version :thumb do
        process resize_to_fill: [50, 50]
    
        def full_filename(for_file = model.logo.file)
          parts     = for_file.split('.')
          extension = parts[-1]
          name      = parts[0...-1].join('.')
          "#{name}_#{version_name}.#{extension}"
        end
      end
    end
    

    The result will be following:

    /Users/user/app/uploads/1x1.gif
    /Users/user/app/uploads/1x1_thumb.gif