Skip to content

How to: Use a timestamp in file names

pouleta edited this page Oct 8, 2014 · 5 revisions

You can include a timestamp in filenames overriding the filename as you can read in Carrierwave docs:

class PhotoUploader < CarrierWave::Uploader::Base
  def filename
    @name ||= "#{timestamp}-#{super}" if original_filename.present? and super.present?
  end

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

Don't forget to memoize the result in an instance variable or you might get different timestamps written to the database and the file store.

(Related: How to: Create random and unique filenames for all versioned files)

Clone this wiki locally