Skip to content

Instantly share code, notes, and snippets.

@coorasse
Forked from pelgrim/old_file_killer.rb
Last active October 16, 2023 14:25
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coorasse/e355a9055474fe0b9aa509ccce12d4fc to your computer and use it in GitHub Desktop.
Save coorasse/e355a9055474fe0b9aa509ccce12d4fc to your computer and use it in GitHub Desktop.
A Ruby on Rails script to delete files older than X days in a given directory.
# A Ruby On Rails script to delete files older than X days in a given directory.
# Quickly written by @coorasse
class FilesCleaner
def self.call(days = 1)
Dir.glob(Rails.root.join('path', 'to', 'folder', '*')).each do |filename|
File.delete(filename) if File.mtime(filename) < days.days.ago
end
end
end
# call with FilesCleaner.call
@NickMoignard
Copy link

NickMoignard commented Mar 18, 2019

This is pretty cool man

@DvirM
Copy link

DvirM commented Apr 23, 2019

Should add handling for subfolders in this folder otherwise, your script will fail.

@colleenbprice
Copy link

Shouldn't it be File.mtime(filename) < X.days.ago since you are comparing times? Less means older than.

@SachinRJadhav
Copy link

If I want to delete files in rails public folder what should be the change in this
Dir.glob(Rails.root.join('path', 'to', 'folder', '*'))?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment