使用Carrierwave上傳圖片, 我想寫1個函數來處理我的所有圖片包含幾種尺寸。如何將變量傳遞給像@ photo_main.file.url(:img_120x120)這樣的方法調用?
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
怎麼能這樣做?
UPDATE 1:
與失敗:::的ActionView模板::錯誤(未定義的方法`文件」的零:NilClass): 1:.ruler 2: 3:// = show_avatar_profile (@ profile.id) 4:= show_avatar_new(@ profile.id, 「96×96」)
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
我不確定'url(size)'是在CarrierWave中獲取特定版本圖像的正確方法,您是否也可以發佈您的上傳器代碼? –