Is there an easier way to insert a timestamp into a filename from Ruby?

Is there an easier way to insert a timestamp into the filename?

def time_stamped_file(file)
  file.gsub(/\./,"_" + Time.now.strftime("%m-%d_%H-%M-%S") + '.') 
end

f = "test.txt"
puts time_stamped_file(f) 


=> test_01-24_12-56-33.txt

      

+3


source to share


3 answers


Not necessarily "simpler", but here's a slightly more canonical and reliable way to do it:



def timestamp_filename(file)
  dir  = File.dirname(file)
  base = File.basename(file, ".*")
  time = Time.now.to_i  # or format however you like
  ext  = File.extname(file)
  File.join(dir, "#{base}_#{time}#{ext}")
end

timestamp_filename("test.txt")     # => "./test_1359052544.txt"
timestamp_filename("test")         # => "./test_1359052544"
timestamp_filename("dir/test.csv") # => "dir/test_1359052544.csv"

      

+6


source


If you are just trying to create a file with a unique name and do not have to contain the original filename, you can use the built-in Tempfile class:



require 'tempfile'

file = Tempfile.new('test')
file.path
#=> "/var/folders/bz/j5rz8c2n379949sxn9gwn9gr0000gn/T/test20130124-72354-cwohwv"

      

+2


source


If you want a shorter approach (and don't care too much about timestamp precision), you can take a Paperclip -like approach as mentioned in the SO post below.

Paperclip - How to create a timestamp attached to the filename?

+1


source







All Articles