|
| 1 | +# encoding: utf-8 |
| 2 | + |
| 3 | +class AvatarUploader < CarrierWave::Uploader::Base |
| 4 | + |
| 5 | + # Include RMagick or MiniMagick support: |
| 6 | + # include CarrierWave::RMagick |
| 7 | + include CarrierWave::MiniMagick |
| 8 | + |
| 9 | + # Choose what kind of storage to use for this uploader: |
| 10 | + storage :file |
| 11 | + # storage :fog |
| 12 | + |
| 13 | + # Override the directory where uploaded files will be stored. |
| 14 | + # This is a sensible default for uploaders that are meant to be mounted: |
| 15 | + def store_dir |
| 16 | + "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" |
| 17 | + end |
| 18 | + |
| 19 | + # Provide a default URL as a default if there hasn't been a file uploaded: |
| 20 | + def default_url |
| 21 | + ActionController::Base.helpers.asset_path("avatars/profile-pic.jpg") |
| 22 | + end |
| 23 | + |
| 24 | + # Process files as they are uploaded: |
| 25 | + # process :scale => [200, 300] |
| 26 | + # |
| 27 | + # def scale(width, height) |
| 28 | + # # do something |
| 29 | + # end |
| 30 | + |
| 31 | + # Create different versions of your uploaded files: |
| 32 | + version :thumb do |
| 33 | + process :resize_to_fit => [50, 50] |
| 34 | + end |
| 35 | + |
| 36 | + version :medium do |
| 37 | + process :resize_to_fit => [300, 300] |
| 38 | + end |
| 39 | + |
| 40 | + # Add a white list of extensions which are allowed to be uploaded. |
| 41 | + # For images you might use something like this: |
| 42 | + def extension_white_list |
| 43 | + %w(jpg jpeg gif png) |
| 44 | + end |
| 45 | + |
| 46 | + # Override the filename of the uploaded files: |
| 47 | + # Avoid using model.id or version_name here, see uploader/store.rb for details. |
| 48 | + def filename |
| 49 | + "#{secure_token}.#{file.extension}" if original_filename |
| 50 | + end |
| 51 | + |
| 52 | + protected |
| 53 | + def secure_token(length=16) |
| 54 | + var = :"@#{mounted_as}_secure_token" |
| 55 | + model.instance_variable_get(var) || model.instance_variable_set(var, SecureRandom.hex(length/2)) |
| 56 | + end |
| 57 | + |
| 58 | +end |
0 commit comments