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

RubyRuby on-Rails-3

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

Ruby has the *nix rm -rf equivalent in the FileUtils module that you can use to delete both files and non-empty folders/directories:

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

To keep the directory itself and only remove its contents:

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

FileUtils.rm_rf(Dir['dir/to/remove/*'])      # shorter version of above

Solution 2 - Ruby

You can run arbitrary commands using backticks like so:

`rm -fr public/cache/*`

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

Solution 3 - Ruby

Great answers here already. You might also be interested to know that Rails 5 has a rake task to do this built-in:

rake tmp:cache:clear # Clear cache files from tmp/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJacobView Question on Stackoverflow
Solution 1 - RubyMarek PříhodaView Answer on Stackoverflow
Solution 2 - RubyJames WatkinsView Answer on Stackoverflow
Solution 3 - RubyGabe KopleyView Answer on Stackoverflow