Skip to content

Instantly share code, notes, and snippets.

@audionerd
Created October 24, 2014 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save audionerd/4703b4ed3ddad82999f7 to your computer and use it in GitHub Desktop.
Save audionerd/4703b4ed3ddad82999f7 to your computer and use it in GitHub Desktop.
Replacing Paperclip file basename with UUID on upload (is there a better way?)
# replace file basename with a UUID when uploaded
# e.g.: avatar.jpg becomes 41bf830f-80cf-4efe-ad90-3b29bc6708b5.jpg
# but don't regenerate a UUID each time file url is accessed
class User < ActiveRecord::Base
has_attached_file :avatar, path: ":basename.:extension"
before_validation { set_avatar_file_name }
def set_avatar_file_name
# replace any NEW filename with a UUID
# NOTE: if user uploads a new image with the exact filename as the most recently assigned UUID, this will break!
if avatar_file_name_changed?
set_avatar_file_name_to_uuid
end
end
def set_avatar_file_name_to_uuid
self.avatar_file_name = SecureRandom.uuid + File.extname(avatar_file_name)
end
end
@audionerd
Copy link
Author

Updated the above to show each attachment should get its OWN callback, e.g.:
before_#{attachment_name}_post_process

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment