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
class Avatar < ActiveRecord::Base

    belongs_to :user

    has_attached_file :image,

        :storage => :s3,
        :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
        :path => "/avatars/:style/:filename",
        :styles => { :medium => "128x128!", :thumb => "50x50!" }

    validates_attachment_presence :image
    validates_attachment_size :image, :less_than => 1.megabyte
    validates_attachment_content_type :image, :content_type => ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']

    before_create :randomize_file_name

    private

    def randomize_file_name

        extension = File.extname(image_file_name).downcase

        self.image.instance_write(:file_name, "#{ActiveSupport::SecureRandom.hex(16)}#{extension}")

    end

end