使用 Carrierwave 上传图像,我想编写 1 个函数来处理我的所有图像,包括多种尺寸。
image_tag @photo_main.file.url(:img_122x145) rescue nil
:img_120x120 是在 Carrierwave 上传器中定义的,但为什么 :img_120x120 分号在其名称前?这是什么格式的?
想要的结果:
def get_avatar(size)
image_tag @photo_main.file.url(size) rescue nil
end
怎么可能做到这一点?
更新 1:
失败:ActionView::Template::Error(nil:NilClass 的未定义方法“文件”):1:.ruler 2:3://= show_avatar_profile(@profile.id)4:= show_avatar_new(@profile.id, “96x96”)
def show_avatar_new(id, size)
puts "size is"
size = size.to_sym
puts size
@photo_main = Photo.where(:attachable_id => id, :attachable_type => "Profile", :main => true, :moderated => true, :approved => true).first
@photo = Photo.where(:attachable_id => id, :attachable_type => "Profile", :moderated => true, :approved => true).first
if @photo_main
image_tag @photo_main.file.url(size)
else
image_tag @photo.file.url(size)
end
end
更新 2:
class PhotoUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
CarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:]\.\-\+]/
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :img_48x48 do
process :resize_to_fill => [48, 48]
end
version :img_58x58 do
process :resize_to_fill => [58, 58]
end
version :img_75x75 do
process :resize_to_fill => [75, 75]
end
version :img_96x96 do
process :resize_to_fill => [96, 96]
end
# Used in search results,
version :img_122x145 do
process :resize_to_fill => [122, 145]
end
version :img_200x200 do
process :resize_to_fill => [200, 200]
end
protected
def secure_token(length=32)
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.hex(length/2))
end
def delete_empty_upstream_dirs
path = ::File.expand_path(store_dir, root)
Dir.delete(path) # fails if path not empty dir
path = ::File.expand_path(base_store_dir, root)
Dir.delete(path) # fails if path not empty dir
rescue SystemCallError
true # nothing, the dir is not empty
end
end