Removing directories older than x days old

Hi, I am trying to write a script that will remove directories that are
older than 5 days old. I can’t seem to get the datetime for the
directory to be usable for comparison.

require ‘fileutils’

class CleanupDirs
def cleanup()
Dir.foreach("/mydir/") do |entry|
puts entry
etime = File.stat(entry)
vAgeInDays = ageInDays( etime.ctime )
if vAgeInDays > 5
Dir.delete(entry)

  end
end

end

def ageInDays(days)
ydate = Time.new
ydate = ydate - ( 24 * 60 * 60 * days)
return ydate
end
end

CleanupDirs.new.cleanup

I keep getting the error Time can’t be coerced into Fixnum (TypeError).

Can someone point out what I am doing wrong?

TIA

On Tue, Nov 22, 2011 at 11:27 AM, Multicom D.
[email protected] wrote:

etime = File.stat(entry)
ydate = ydate - ( 24 * 60 * 60 * days)
You do not want to substract the number of seconds from a timestamp to
get the age. For the age of something you need to calculate now -
timestamp.

return ydate
end
end

CleanupDirs.new.cleanup

I keep getting the error Time can’t be coerced into Fixnum (TypeError).

Can someone point out what I am doing wrong?

Better do

def age_in_days(time_stamp)
(Time.now - time_stamp) / (24 * 60 * 60)
end

The whole thing might be a tad more efficient if you do

def age_in_days(time_stamp, now = Time.now)
(now - time_stamp) / (24 * 60 * 60)
end

now = Time.now

if age_in_days(ts, now) > 5

end

Also that way you have a single reference point which might make some
things easier.

Few more remarks: you do not need a class for this as the only method
(cleanup) does not have any parameters and does not work with instance
state.

Note also that you might rather want to use #mtime instead of #ctime.

You should also treat entries different which are directories. Maybe
you rather want to use Find.find or a glob pattern like Dir[’**/*’].

Kind regards

robert

Thank you Robert. Its working now.