Paperclip - rename file before saving

user984621 picture user984621 · Apr 23, 2012 · Viewed 7.7k times · Source

I use this method for renaming the image before the saving:

  def rename_avatar
    self.avatar.instance_write :file_name, Time.now.to_i.to_s
  end

  before_post_process :rename_avatar

The image is renamed by the current time, but there's not added the file type, instead of 1334487964.jpg is saved only 1334487964..

What I missing there? I thought :file_name contains only the file name - without the file type

Answer

user984621 picture user984621 · Apr 30, 2012

This is the way how I fix my issue:

  def rename_avatar
    #avatar_file_name - important is the first word - avatar - depends on your column in DB table
    extension = File.extname(avatar_file_name).downcase
    self.avatar.instance_write :file_name, "#{Time.now.to_i.to_s}#{extension}"
  end