First of all – Why?
Chances are you already know why you need abc/jkl/xyz file paths since you’re reading this. If not, you may at some point stumble upon the problem of having too many files uploaded into one directory. Hard drives and OSes have limits for these things, you know. In fact, in most cases you won’t even get a notice. Files will just stop saving where they should. What a horrible bug to tackle. If you’re on Rails and using Paperclip – you can prevent this with a few lines of code.
In your config/initializers/ create a file named “paperclip_extensions.rb” and type the following.
hash = Digest::MD5.hexdigest(attachment.instance.id.to_s + 'secret_word')
hash_path = ''
3.times { hash_path += '/' + hash.slice!(0..2) }
hash_path[1..12]
end
Adding a ‘secret word’ is not necessary. I just threw it in there for fun.
The 2nd line takes id of your attachment and makes hash out of it. The 4th line then chops up the beginning hash string into 3 pieces, and makes them into a ‘abc/jkl/xyz’ kind of path.
You may notice that we’re only using id to generate hash – meaning that two different models with the same id would create the same path. So what? We aren’t trying to prevent collisions. We’re only making sure the directory structure is nice and even. You know, no huge piles of files in one place.
But this is not all!
In your model you now have the new token that you can use for Paperclip paths. :hashed_path is that which I’m talking about. Now this token can live inside our Paperclip path string, yay.
:path => '/foo/bar/:hashed_path/filename.ext'
Do this early to omit a little bit of horrible pain later. (If your application is upload-heavy that is).
Your example was very helpful, thanks again
Perfect! works like a charm, thanks
The current example uses a depreciated interpolation assignment. It’s pretty simple to fix though by replacing:
with
[...] znalazłem tutaj. Jest ono proste jak konstrukcja cepa a jego wdrożenie nie zajmuje zbyt wiele [...]