Skip to content

How To: Move version name to end of filename, instead of front

scottwb edited this page Jul 9, 2011 · 1 revision

Consider an uploader like this:

class AvatarUploader < CarrierWave::Uploader::Base
  version :square do
    process :crop_to_square
    version :large do
      process :resize_to_fit => [512,512]
    end
    version :small do
      process :resize_to_fit => [64, 64]
    end
  end
end

An uploaded file named foo.jpg will get stored with the following versions:

  • foo.jpg
  • square_foo.jpg
  • square_large_foo.jpg
  • square_small_foo.jpg

These do not group nicely when sorted by filename. If you prefer to have the version name (e.g.: square_large) suffixed to the filename instead of prefixed, you can override the methods that generate these with a monkey-patch like this:

module CarrierWave
  module Uploader
    module Versions
      def full_filename(for_file)
        parent_name = super(for_file)
        ext         = File.extname(parent_name)
        base_name   = parent_name.chomp(ext)
        [base_name, version_name].compact.join('_') + ext
      end

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

This causes the following version filenames to be generated instead:

  • foo.jpg
  • foo_square.jpg
  • foo_square_large.jpg
  • foo_square_small.jpg
Clone this wiki locally