Skip to content

Instantly share code, notes, and snippets.

@ryancheung
Forked from audionerd/gist:4703b4ed3ddad82999f7
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryancheung/732c953af54431ed13e4 to your computer and use it in GitHub Desktop.
Save ryancheung/732c953af54431ed13e4 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment