From f32036eb0fe84ab655c62c1b43ba494e015741cc Mon Sep 17 00:00:00 2001
From: Giovanne Marcelo <gms15@inf.ufpr.br>
Date: Wed, 11 Jan 2017 23:00:16 -0200
Subject: [PATCH] now the task only executes if the size of attachments exceed
 the limit

---
 lib/tasks/attachment_maintaining_service.rake | 22 +++++++++++++------
 1 file changed, 15 insertions(+), 7 deletions(-)

diff --git a/lib/tasks/attachment_maintaining_service.rake b/lib/tasks/attachment_maintaining_service.rake
index 6c95f771..701366d5 100644
--- a/lib/tasks/attachment_maintaining_service.rake
+++ b/lib/tasks/attachment_maintaining_service.rake
@@ -3,20 +3,28 @@ require 'fileutils'
   namespace :attachment_maintaining_service do
 
     desc 'Removing attachments'
-    task remove_attachments: :environment do
-      sort_directories.first(10).each do |dir|
-        FileUtils.rm_r(dir)
+    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
       end
     end
 
     private
 
-    def sort_directories
-      Dir[dir_path].sort_by{ |f| File.atime(f) }
+    def attachments_size(dir)
+      `du -s #{dir} | cut -f 1`.to_i
     end
 
-    def dir_path
-      Rails.root.join('public','attachments','*').to_s
+    def sort_attachments(attachments_path)
+      Dir[attachments_path].sort_by{ |f| File.atime(f) }
+    end
+
+    def attachments_path
+      Rails.root.join('public','attachments').to_s
     end
 
   end
-- 
GitLab