diff --git a/lib/tasks/attachment_maintaining_service.rake b/lib/tasks/attachment_maintaining_service.rake index 701366d5d810b390b79ec0c41f21cf3b29162446..13e3f6a29bccc88b0a2d3d09cb075d2edb5a5852 100644 --- a/lib/tasks/attachment_maintaining_service.rake +++ b/lib/tasks/attachment_maintaining_service.rake @@ -2,28 +2,24 @@ require 'fileutils' namespace :attachment_maintaining_service do - desc 'Removing attachments' - task remove_attachments: :environment do |t, args| - args.with_defaults(limit: 10.gigabytes) - path = attachments_path + "/*" - if attachments_size(attachments_path) > args.limit - sort_attachments(path).first(10).each do |dir| - FileUtils.rm_r(dir) - end + desc 'Removing attachments using random politic' + task :remove_attachments, [:limit] => :environment do |t, args| + args.with_defaults(limit: 10.gigabyte) + attachments_dir = attachment_dir + "/*" + + while dir_size(attachment_dir) > args.limit.to_i do + # TODO now the politic is random, verify if politics like LRU or NRU improve the efficiency + FileUtils.rm_r Dir[attachments_dir].sample end end private - def attachments_size(dir) - `du -s #{dir} | cut -f 1`.to_i - end - - def sort_attachments(attachments_path) - Dir[attachments_path].sort_by{ |f| File.atime(f) } + def dir_size(dir) + `du -sb #{dir} | cut -f 1`.to_i end - def attachments_path + def attachment_dir Rails.root.join('public','attachments').to_s end