以下是一个例子:
应用程序/模型/ book.rb
class Advertisement < ActiveRecord::Base
enum kind: { magazine: 0, newspaper: 1 }
mount_uploader :main_pic, BookMainPicUploader
# ...
end
应用程序/上传/ book_main_pic_uploader.rb
class BookMainPicUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :fog
def store_dir
"uploads/featured/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(jpg jpeg gif png)
end
version :normal do
process resize_to_fill: [800, 400]
end
version :square do
process resize_to_fill: [400, 400]
end
end
上述代码会为每种类型的书籍创建正常版本和方形版本,但我们只想生成杂志的正常版本和仅报纸的正方形版本。
有可能实现吗?
答案 0 :(得分:0)
您需要将version
条件选项传递给if
方法。
class BookMainPicUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :fog
def store_dir
"uploads/featured/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(jpg jpeg gif png)
end
version :normal, if: :is_magazine? do
process resize_to_fill: [800, 400]
end
version :square, if: :is_newspaper? do
process resize_to_fill: [400, 400]
end
private
def is_magazine? picture
model.magazine?
end
def is_newspaper? picture
model.newspaper?
end
end