Apply processor with paperclip if condition it's true

你。 提交于 2019-12-10 15:54:22

问题


I have a model with paperclip ruby gem. I defined an attached file with 2 processors (thumbnail and watermark).

The question is if exist the way to apply the watermark processor if condition is true. (the idea it's not define new attached_files without watermark processor)

Thanks in advance.

I try using this code, but dosen't works. If the field eid exist process with watermark else if null process only thumbnail

:processors => lambda { |a|
                if a.eid.nil?
                        [:thumbnail,:watermark]
                else
                        [:thumbnail]
                end
                },

回答1:


The processors option could accept proc, so you could make your processors depend on instance:

:processors => lambda{ |attachment|
   attachment.instance.some_method_to_get_processors_here
},



回答2:


According to the current Paperclip docs, the lambda is called differently for processors than for styles. Styles are passed the attachment:

class User < ActiveRecord::Base
  has_attached_file :avatar, :styles => lambda { |attachment| { :thumb =>   
    (attachment.instance.boss? ? "300x300>" : "100x100>") } }
end

With attachment.instance being an instance of your model. But processors are passed the instance itself:

class User < ActiveRecord::Base
  has_attached_file :avatar, :processors => lambda { |instance| instance.processors }
  attr_accessor :watermark
end

This latter example worked for me. I had User#processors return an array of processors (but if you just want the default processor, return [:thumbnail], not an empty array).



来源:https://stackoverflow.com/questions/8590822/apply-processor-with-paperclip-if-condition-its-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!