I transitioned from carrierwave to paperclip last week and am having trouble randomizing the filename of an upload. I had a custom method from carrierwave that took care of this, but can’t find the equivalent in paperclip.
I have a Logo model with photo attachment and store the files in a single directory. I found an article on the wiki about normalizing filenames, but that isn’t the same thing. Any help would be appreciated.
Thank you. I think I was misunderstanding the obfuscation section of the docs, thinking it still stored the original filename in the database. Is there an easy way I can shorten the hash?
This doesn’t work, but something like this? :hash[0..9].:extension
Update:
Taking a closer look, paperclip does store the original filename in the database, and a hashed version on s3. Unfortunately this will not work for my case as I am trying to randomize the filename stored in the database. Sorry for not making that point clearer.
Final Update:
Going back to the Wiki, under helpful articles, an article for normalizing filenames, referenced another article for randomizing filenames stored in the database.
So in the end, I followed that and added a private method and before_create method.
def randomize_file_name
extension = File.extname(photo_file_name).downcase
self.photo.instance_write(:file_name, "lgo#{Digest::SHA1.hexdigest((rand(12123123423) * Time.now.to_i).to_s)[0..9]}#{extension}")
end
This is now working as expected and now I also understand more about the interpolations. Both are useful to know depending on what your needs are. I should have dug deeper into the wiki.