augustl (owner)

Revisions

gist: 9323 Download_button fork
public
Public Clone URL: git://gist.github.com/9323.git
attachment.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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