How to set a paper clip style style only if the contenttype is an image?

I am using the following:

has_attached_file :file,:styles => { :thumbnail => '320x240!'},:url => "/images/:attachment/:id/:style/:basename.:extension",:path => ":rails_root/public/images/:attachment/:id/:style/:basename.:extension" validates_attachment_content_type :file, :content_type => [ 'image/gif', 'image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/jpg' ] 

Download both images and videos. If I use :style =>{} , then the image will not be uploaded. I want to use the :style method only if the content type of the file is an image.

+6
source share
2 answers

You can use the condition inside lambda, sorry for the ugly formatting:

 has_attached_file :file, :styles => lambda { |a| if a.instance.is_image? {:thumbnail => "320x240!"} end } def is_image? return false unless asset.content_type ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg'].include?(asset.content_type) end 
+5
source

Update 2016:

Most of the answers are saved, but you need to return an empty hash if it does not match the expected type (for example, a PDF that you do not want to process instead of an image), otherwise you will encounter TypeError - can't dup NilClass .

An example using ternary for patience:

 has_attached_file :file, :styles => lambda { |a| a.instance.is_image? ? {:thumbnail => "320x240!"} : {} } 
+2
source

Source: https://habr.com/ru/post/926611/


All Articles