From 34f9589c6b152e6d5202d66760b1fa7e9bd88fb2 Mon Sep 17 00:00:00 2001
From: Istvan DEMTER <demeter.istvan@gmail.com>
Date: Tue, 13 Apr 2010 01:09:47 +0200
Subject: [PATCH] Store file in "%y%m/%d/" format sub dir to prevent directory index growing too large

---
 app/models/attachment.rb |   10 +++++++---
 1 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/app/models/attachment.rb b/app/models/attachment.rb
index c752e0e..d35c170 100644
--- a/app/models/attachment.rb
+++ b/app/models/attachment.rb
@@ -15,7 +15,8 @@
 # along with this program; if not, write to the Free Software
 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
-require "digest/md5"
+require 'digest/md5'
+require 'fileutils'
 
 class Attachment < ActiveRecord::Base
   belongs_to :container, :polymorphic => true
@@ -76,6 +77,8 @@ class Attachment < ActiveRecord::Base
     if @temp_file && (@temp_file.size > 0)
       logger.debug("saving '#{self.diskfile}'")
       md5 = Digest::MD5.new
+      path = File.dirname diskfile
+      FileUtils.mkdir_p(path) unless File.directory?(path)
       File.open(diskfile, "wb") do |f| 
         buffer = ""
         while (buffer = @temp_file.read(8192))
@@ -178,9 +181,10 @@ private
       # keep the extension if any
       ascii << $1 if filename =~ %r{(\.[a-zA-Z0-9]+)$}
     end
-    while File.exist?(File.join(@@storage_path, "#{timestamp}_#{ascii}"))
+	sub_path = "#{timestamp[0..3]}/#{timestamp[4..5]}"
+    while File.exist?(File.join(@@storage_path, sub_path, "#{timestamp}_#{ascii}"))
       timestamp.succ!
     end
-    "#{timestamp}_#{ascii}"
+	"#{sub_path}/#{timestamp}_#{filename}"
   end
 end
-- 
1.7.0

