Home » Ruby » How to delete all contents of a folder with Ruby-Rails?

How to delete all contents of a folder with Ruby-Rails?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have a public/cache folder which has files and folders. How can I completely empty that folder using a rake task?

Answers:

Ruby has the *nix’s rm -rf in the the FileUtils module that you can use to delete both files and non-empty folders

FileUtils.rm_rf('dir/to/remove')

To keep the directory itself and only remove its contents:

FileUtils.rm_rf(Dir.glob('dir/to/remove/*'))

Questions:
Answers:

You can run arbitrary commands using the tilted single-quote (next to the tilde) like so:

`rm -fr public/cache/*`

This may be more platform-dependent than what you want, but it opens up a lot of possibilities.