Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 297
AnApprentice Avatar asked Jan 04 '17 06:01

AnApprentice


1 Answers

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
  • More information in Wiki: How to: Migrate from one model to another
  • MVP example: https://gist.github.com/itsNikolay/2394f84f31db33d4c3dc6634068b0259
like image 122
itsnikolay Avatar answered Oct 21 '22 21:10

itsnikolay