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 (undefined method `file' for 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