我有一个包含csv个文件的目录,名为reports

我要删除reports文件夹中超过X天的所有文件.

这样可以很好地删除所有文件:

FileUtils.rm_rf("reports/.", secure: true)

但我想要的过滤器只删除X天数之前的文件.

多么?

推荐答案

您可以列出所有文件名,然后使用File.stat判断每个文件的修改时间并删除每个文件.

例如,您可以使用以下代码:

# will count X days older than "reference_time"
reference_time = Time.now

# use the following value to delete files older than 30 days
delete_older_than = 30 * (24 * 3600) # value in seconds

all_files = Dir['reports/*']
all_files.each do |relative_file_name|
  # not really necessary, but I like to work with full file paths
  file_path = File.expand_path(relative_file_name)

  # if you want to be strict and delete only files (e.g. not folders),
  # this line skips any non-files.
  next unless File.file?(file_path)

  st = File.stat(file_path)  
  # modification time is at st.mtime

  if st.mtime < (reference_time - delete_older_than)
    File.unlink(file_path)
  end
end

Ruby-on-rails相关问答推荐

Grape api (rails) - 未初始化常量 Endpoints::TodoAPI (NameError)

Ruby on Rails 更新触发了 Mailer 函数中的 ArgumentError

在单个继承表和另一个表中的类之间建立多对多关联

Rails 5:如何从数据库中删除列?

Devise + Omniauth - 如何传递额外的参数?

如何使用 Vim 插入 ERB 标签?

rails s和bundle exec rails s有什么区别?

PostgreSQL 无间隙序列

Rails Scope 返回 all 而不是 nil

如何从 Rails 路由中删除控制器名称?

耙路由错误缺少:路由定义上的操作键

不允许请求来源:使用 Rails5 和 ActionCable 时的 http://localhost:3001

Rails:从视图内渲染视图(不是部分视图)

rails 单数资源还是复数?

从 Rails 中的控制器调用辅助方法时出现未定义的方法

Rails 3 返回 HTTP 406 Not Acceptable?

你如何undo撤消Bundle 安装 --without

从任何编码强制字符串为 UTF-8

Vagrant上的Rails 4.2服务器端口转发不起作用

Ruby on Rails:Cucumber:我如何获取单个功能?