forked from carrierwaveuploader/carrierwave
-
Notifications
You must be signed in to change notification settings - Fork 0
How to: Use file`s MD5 as filename
shekibobo edited this page Apr 2, 2013
·
6 revisions
Inside your uploader class:
def md5
chunk = model.send(mounted_as)
@md5 ||= Digest::MD5.hexdigest(chunk.read)
end
def filename
@name ||= "#{md5}#{File.extname(super)}" if super
end
Optionally, save the md5 in the DB too. Mongoid example:
class Asset
include Mongoid::Document
...
field :md5
mount_uploader :data, AssetUploader
validates_uniqueness_of :md5
before_save :update_data_attributes
private
def update_data_attributes
if data.present? && data_changed?
self.md5 = data.md5
end
end
This is also good to ensure unique/remove duplicates. Just a note: Mongoid sets the slug in a before_save block, you might want to move it to validation to make this validation work.