Skip to content

How to: Customize your version file names

Cayo Medeiros edited this page Sep 18, 2018 · 8 revisions

In the current version of CarrierWave if you have an uploader defined like this:

class LogoUploader < CarrierWave::Uploader::Base 
  # ... 
  def filename 
    "original.#{model.logo.file.extension}" if original_filename 
  end 
  version :small do 
    process :resize_to_fit => [190, 190] 
    process :convert => 'png' 
  end 
  version :icon do 
    process :resize_to_fill => [50, 50] 
    process :convert => 'png' 
  end 
  # ... 
end

and attach a file name somefile.jpg, you will end up with files named original.jpg, original_small.png and original_icon.png respectively.

If you want to set a specific file name for each version, you cannot simply nest another filename method inside the version. Instead, you will need to override the full_filename method that is originally defined in the CarrierWave::Uploader::Versions module. An example would look like this:

  def filename 
    "original.#{model.logo.file.extension}" if original_filename 
  end 
  version :small do 
    process :resize_to_limit => [190,190] 
    process :convert => 'png' 
    def full_filename (for_file = model.logo.file) 
      "small.png" 
    end 
  end 
  version :icon do 
    process :resize_to_fill => [50,50] 
    process :convert => 'png' 
    def full_filename (for_file = model.logo.file) 
      "icon.png" 
    end 
  end 

Given the original example, the result of this code will be a file named original.jpg, plus the version files small.png and icon.png

Clone this wiki locally