Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easier way to insert a time stamp into a file name with Ruby?

Tags:

ruby

Is there an easier way to insert a time stamp in a file name ?

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
like image 976
Darryl Avatar asked Jan 24 '13 18:01

Darryl


2 Answers

Not necessarily "easier," but here's a slightly more canonical and robust 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"
like image 110
Ryan McGeary Avatar answered Sep 27 '22 19:09

Ryan McGeary


If you're just trying to create a uniquely named file and it doesn't have to contain the original filename, you could use the built-in Tempfile class:

require 'tempfile'

file = Tempfile.new('test')
file.path
#=> "/var/folders/bz/j5rz8c2n379949sxn9gwn9gr0000gn/T/test20130124-72354-cwohwv"
like image 24
stef Avatar answered Sep 27 '22 19:09

stef