module Paperclip
module ClassMethods
def randomizes_attachment_file_name name
before_post_process :"randomize_#{name}_file_name"
define_method :"randomize_#{name}_file_name" do |*args|
self.send(name).queue_existing_files_for_delete
extension = File.extname(self.send(:"#{name}_file_name"))
self.send(name).instance_write(:file_name,
"#{ActiveSupport::SecureRandom.hex}#{extension.downcase}")
end
end
end
class Attachment
def queue_existing_files_for_delete #:nodoc:
@queued_for_delete += [:original, *@styles.keys].uniq.map do
|style|
path(style) if exists?(style)
end.compact
end
end
end
This lets me do the following:
class User < ActiveRecord::Base
has_attached_file :avatar
randomizes_attachment_file_name :avatar
end
I had to add the queue_existing_files_for_delete method, because when
reprocessing the old filenames would get forgotten and then never removed.
I have only used this in Rails 2.3.2, I'm not sure if the
ActiveSupport::SecureRandom.hex works in previous versions - you used to
use CGI::Session.generate_unique_id.
I don't have any tests for this yet, and there are probably better ways
to do some of this, but I thought this might be useful for some of you.