Using acts_as_attachment without filenames
The Rails plugin, acts_as_attachment, has recently been improved to not require a filename column in the database. This is useful to anyone who does not want to expose your user’s original filename.
Using acts_as_attachment without filenames is actually very simple. First, your database schema cannot contain a filename column. Second, enhance your class to contain a method to return an appropriate filename. I am using:
def filename
if parent_id
"#{parent_id}_#{thumbnail}.file"
else
"#{id}.file"
end
end
As mentioned in my previous post about acts_as_attachment, I am also altering the default directory structure. Putting it all together, here is my attachment model if we were working with the DVD Cover tutorial.
class DvdCover < ActiveRecord::Base
acts_as_attachment :storage => :file_system,
:content_type => :image,
:thumbnails => { :normal => ‘640×480′, :thumb => ‘100×75′ }
validates_as_attachment
def filename
if parent_id
“#{parent_id}_#{thumbnail}.file”
else
“#{id}.file”
end
end
@@HierarchyLevels = 2
def full_filename(thumbnail = nil)
object = (thumbnail ? thumbnail_class : self)
file_system_path = object.attachment_options[:file_system_path]
parts = [RAILS_ROOT, file_system_path] +
(1..@@HierarchyLevels).map { |i| partial_path(i) } +
[ thumbnail_name_for(thumbnail)]
File.join(parts)
end
protected
# Given i, extract the ith 8-bit hex representation from our primary id.
def partial_path(i)
the_id = (respond_to?(:parent_id) && parent_id) || id
“%02X” % ((the_id >> (8*i)) % 256)
end
end
No comments yet. Be the first.
Leave a reply

