Skip to content

Instantly share code, notes, and snippets.

@augustl
Created September 7, 2008 22:11
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 augustl/9323 to your computer and use it in GitHub Desktop.
Save augustl/9323 to your computer and use it in GitHub Desktop.
require 'digest/sha1'
class Attachment < ActiveRecord::Base
DIRECTORY = 'attachments'
PATH = File.join(Rails.root, 'public', DIRECTORY)
CHARACTERS = %w(a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9)
validates_presence_of :upload
before_create :set_attributes_from_upload
after_create :store_file
attr_accessor :upload
def url
"/#{DIRECTORY}/#{file_name}"
end
private
def set_attributes_from_upload
until unique_file_name?
self.file_name = "#{random_prefix}-#{upload.original_filename}"
end
self.size = upload.size
self.content_type = upload.content_type
end
def unique_file_name?
file_name && !File.file?(full_file_path)
end
def store_file
File.open(full_file_path, "w") do |f|
f.write upload.read
end
end
def full_file_path
File.join(PATH, file_name)
end
def random_prefix
Array.new(4).inject("") {|string, ary| string << characters.rand }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment