class Attachment < ActiveRecord::Base belongs_to :post attr_writer :data include ErrorRaising def before_save self.filename.gsub!(/[^a-z_\.\-0-9]/i, '_') self.filename.gsub!(/^\.+/, '_') end def after_save # Create attachment directory begin Dir.mkdir(self.dir_path) rescue Errno::EEXIST end # Save uploaded file to attachment directory File.open(self.file_path, 'w') do |f| f.write(@data) end @data = nil end def after_destroy # Delete file File.delete self.file_path # Delete directory Dir.delete self.dir_path end # Returns the directory of this attachment, e.g. /forum/public/attachments/12/ def dir_path RAILS_ROOT + RForum::CONFIG[:attachment_path] + "/#{self.id}/" end def file_path self.dir_path + self.filename end def get_file_content self.reload File.read self.file_path end def url "/attachment/#{self.id}/#{self.filename}" end end