如何使用 Ruby-Rails 删除文件夹的所有内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8538427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:35:41  来源:igfitidea点击:

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

rubyruby-on-rails-3

提问by Jacob

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

我有一个public/cache文件夹,里面有文件和文件夹。如何使用 rake 任务完全清空该文件夹?

回答by Marek P?íhoda

Ruby has the *nix rm -rfequivalent in the FileUtilsmodule that you can use to delete both files and non-empty folders/directories:

Rubyrm -rfFileUtils模块中具有 *nix等效项,您可以使用它来删除文件和非空文件夹/目录:

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

回答by James Watkins

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.

这可能比您想要的更依赖于平台,但它开辟了很多可能性。

回答by Gabe Kopley

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

这里已经有了很好的答案。您可能还想知道 Rails 5 有一个内置的 rake 任务来执行此操作:

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