Created
August 9, 2011 14:28
-
-
Save a-chernykh/1134188 to your computer and use it in GitHub Desktop.
CarrierWave extension-aware remote file downloading
This file contains hidden or 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
class AvatarUploader < CarrierWave::Uploader::Base | |
include CarrierWave::MiniMagick | |
def extension_white_list | |
model.skip_avatar_extension_check ? nil : %w(jpg jpeg gif png bmp) | |
end | |
end |
This file contains hidden or 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
class Profile < ActiveRecord::Base | |
mount_uploader :avatar, AvatarUploader | |
attr_accessor :skip_avatar_extension_check | |
def file_avatar_url=(url) | |
begin | |
self.skip_avatar_extension_check = true | |
avatar.download!(url) | |
ensure | |
self.skip_avatar_extension_check = false | |
end | |
path = avatar.path | |
ext = File.extname(path) | |
logger.debug "Downloaded file extension - #{ext}" | |
if ext.blank? && ext = detect_extension(path) | |
logger.debug "Detected extension for avatar - #{ext}" | |
path = path + ".#{ext}" | |
FileUtils.mv(avatar.path, path) | |
avatar.remove! | |
self.avatar = File.open(path) | |
end | |
avatar.send(:check_whitelist!, CarrierWave::SanitizedFile.new(File.open(path))) | |
avatar.store! | |
save! | |
end | |
protected | |
def detect_extension(file_name) | |
mime_type = %x(file --mime-type #{file_name}|cut -f2 -d' ').gsub("\n", "") | |
case mime_type | |
when 'image/jpeg' | |
'jpg' | |
when 'image/jpg' | |
'jpg' | |
when 'image/png' | |
'png' | |
when 'image/gif' | |
'gif' | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A little simplier: