Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carreirwave - How to have the version name created directly from the saved filename

I'm creating a thumb image for the files that have been uploaded on my app. The image names have a timestamp code in them. When I run recreate_versions the thumb image generated also has the timestamp in it but it uses the current timestamp which makes the thumb image name differ from the original filename.

So I figured a fix would be to have a custom filename for the thumb image. Basically have 'thumb_' + 'original filename'.

   version :thumb do
     process :resize_to_limit => [110, nil]

     def full_filename(for_file = model.image_value.file)
     'thumb_' + File.basename(model.image_value.path).to_s
     end
   end

  def filename(for_file = model.image_value.file)
   "#{model.id}" + "-v#{timestamp}" + "-" + "#{model.name}" + ".png" if original_filename.present?
  end

  def timestamp
    var = :"@#{mounted_as}_timestamp"
    model.instance_variable_get(var) or model.instance_variable_set(var, Time.now.to_i)
  end

This seemed like an easy fix but for some reason when I run recreate_versions the thumb image is generated with the current timestamp in it, not the timestamp in the name of the original filename. From what I understand it should grab the value stored in the DB that is the raw filename and add it to the end of 'thumb_'. But somehow its changing the timestamp in the name.

stored filename                      =       1-v1474175808-model-name.png
Item.find(1).image_value_url(:thumb) = thumb_1-v1474175808-model-name.png #this works correctly and looks for the correct filename
thumb filename saved                 = thumb_1-v1472111618-model-name.png #thumb saved is different. For some reason has a different timestamp in name

I thought maybe def full_filename isnt being run, but if I change it to something else the thumb filename saved is changed to what is in def full_filename.

Not sure what is going on here. hopefully someone can help. If it looks like it should work please let me know, atleast that will clarify that it could be something I'm not looking at.

like image 315
Rob Avatar asked Sep 19 '16 10:09

Rob


1 Answers

Ended up having to use the generated url and using slice! on the url to leave just the image name.

   version :thumb do
     process :resize_to_limit => [110, nil]

    def full_filename(for_file = model.image_value.file)
      raw_file_name = model.image_value.slice!(0..65)
     'thumb_' + raw_file_name
     end

  end
like image 69
Rob Avatar answered Nov 13 '22 22:11

Rob