Skip to content

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

omitter edited this page Apr 4, 2017 · 7 revisions

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 as the following version filenames:

  • 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 full_filename and original_filename methods in your uploader class as follows:

class AvatarUploader < CarrierWave::Uploader::Base
  # ...

  def full_filename(for_file)
    if parent_name = super(for_file)
      extension = File.extname(parent_name)
      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("_") + extension
    end
  end

  def full_original_filename
    parent_name = super
    extension = File.extname(parent_name)
    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("_") + extension
  end
end

Now the following version filenames will be generated:

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