Last active
December 28, 2015 10:18
-
-
Save bosskovic/7484993 to your computer and use it in GitHub Desktop.
Example of using carrierwave to manage file uploads
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 'carrierwave/processing/mime_types' | |
class AvatarUploader < CarrierWave::Uploader::Base | |
include CarrierWave::MiniMagick | |
include CarrierWave::Processing::MiniMagick | |
include CarrierWave::MimeTypes | |
# Changes the file content_type using the mime-types gem | |
process :set_content_type | |
# Strips out all embedded information from the image | |
process :strip | |
# Changes the image encoding format to the given format | |
process :convert => 'jpg' | |
# Adds a new version to the uploader | |
version :large do | |
# Resize the image to fit within the specified dimensions while retaining | |
# the original aspect ratio. Will only resize the image if it is larger | |
# than the specified dimensions. The resulting image may be shorter or | |
# narrower than specified in the smaller dimension but will not be larger | |
# than the specified values. | |
process :resize_to_limit => [600, 450] | |
end | |
version :profile do | |
# Resize the image to fit within the specified dimensions while retaining | |
# the aspect ratio of the original image. If necessary, crop the image in the | |
# larger dimension. | |
process :resize_to_fill => [250, 250] | |
end | |
version :thumb do | |
process :resize_to_fill => [60, 60] | |
end | |
# allowed file extensions can be listed in extension_white_list method. | |
# Trying to upload a file with a different extension | |
# would result in displaying an error. | |
def extension_white_list | |
%w(jpg jpeg gif png) | |
end | |
# Location where the uploaded files are stored can be changed | |
# by overriding the store_dir method | |
def store_dir | |
"public/#{model.class.to_s.underscore}/#{model.uuid}/avatar" | |
end | |
# For storing files outside the project root folder, | |
# cache_dir should be overriden | |
def cache_dir | |
"#{Rails.root}/tmp/uploads" | |
end | |
def default_url | |
"application/default_avatar_#{version_name}.png" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment