Created
September 7, 2008 22:11
-
-
Save augustl/9323 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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