Conditional versions/process with Carrierwave

2020-07-16 08:37发布

I have this uploader class

class ImageUploader < CarrierWave::Uploader::Base

  include CarrierWave::RMagick

  process :resize_to_limit => [300, 300]

  version :thumb do
    process :resize_to_limit => [50, 50]
  end

 ...

Which will process the original file to 300x300 and save a thumb version.

I would like to be able to make a small/thumb version only based on a boolean on my model?

So I did this

if :icon_only?
 process :resize_to_limit => [50, 50]
else
  process :resize_to_limit => [300, 300]
end

protected

 def icon_only? picture
   model.icon_only?
 end

But it always ended up in 50x50 processing. Even when I did like this

 def icon_only? picture
   false
 end

I might got my syntax up all wrong with the : but i also tried asking

if icon_only?

Which told me there was no method name like that.Im lost...

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-07-16 09:03

As @shioyama pointed out, one can use :if to specify the condition.

However, doing the inverse condition (e.g. !icon_only?) requires a bit of work.

process :resize_to_limit => [300, 300], :if => Proc.new {|version, options| !version.send(:icon_only?, options[:file])} do
查看更多
戒情不戒烟
3楼-- · 2020-07-16 09:07

Use an :if conditional, like so:

process :resize_to_limit => [50, 50], :if => :icon_only?
process :resize_to_limit => [300, 300], :if => ...

I haven't actually tried this but it's documented in the code, so it should work.

查看更多
登录 后发表回答