I’ve been looking for a solution to change the filenames of the uploaded files and came across the great tutorial at http://the.railsi.st/2007/8/21/how-to-customize-attachment_fu-file-names/ but it was not what i was exactly looking for. I had issues with viewing the saved files because the thumbnail property does not exist for the new attachment etc.
I’m posting what I did and it changes the filenames to what ever we specify.. Works for me, and hopefully it will work for someone else as well.. :)
checkout the pastie for a better view of the code http://pastie.caboo.se/161062
class Photo < ActiveRecord::Base
#Options for has_attachment
has_attachment :content_type => :image,
:storage => :file_system,
:size => 1.kilobyte .. 10.megabytes,
:resize_to => '500>',
:thumbnails => { :thumb => '125' },
:path_prefix => 'public/images/product_pics',
:processor => 'MiniMagick'
validates_as_attachment
belongs_to :product
#Filename changing stuff, these methods resides in attachement_fu plugin files..
#and we are just modifying them to fit our needs and putting them in our model
#so other models will not be effected
def full_filename(thumbnail = nil)
file_system_path = (thumbnail ? thumbnail_class : self).attachment_options[:path_prefix]
@thumb = self.thumbnail unless (@thumb = thumbnail) #checks if thumbnails info already exist
File.join(RAILS_ROOT, file_system_path, self.product.code, thumbnail_name_for(@thumb, self.product.code))
end
#Change the filenames and thumbnail suffixes
def thumbnail_name_for(thumbnail = nil, asset = nil)
suffix = "_#{thumbnail}" unless thumbnail.blank? #sets suffix by the name of the thumbnail set in has_attachment options
extension = filename.scan(/\.\w+$/) # extracts extension
return "#{asset}#{suffix}#{extension}" # change the filename to fit your needs
end
before_thumbnail_saved do |record, thumbnail|
thumbnail.product_id = record.product_id
end
end