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

Owner

augustl

Revisions

  • ca8da5 leethal Wed Sep 17 03:41:15 -0700 2008
  • a651b7 leethal Sun Sep 07 18:14:34 -0700 2008
  • e1d833 leethal Sun Sep 07 18:11:55 -0700 2008
  • c98032 leethal Sun Sep 07 18:08:22 -0700 2008
  • f2b5d5 leethal Sun Sep 07 18:06:19 -0700 2008
  • 84d608 leethal Sun Sep 07 18:05:57 -0700 2008
  • 31c7cc leethal Sun Sep 07 18:05:10 -0700 2008
  • 067212 leethal Sun Sep 07 18:03:06 -0700 2008
  • 5e3234 leethal Sun Sep 07 18:01:54 -0700 2008
  • 5f8c74 leethal Sun Sep 07 18:01:12 -0700 2008