Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Paperclip style work only if contenttype is 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' ]

To upload both images and video. If I use :style =>{} then image does not upload. I want to use :style method only if content type of file is image.

like image 439
Manish Avatar asked Sep 30 '12 13:09

Manish


2 Answers

You can use condition inside of lambda, sorry about 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
like image 164
iouri Avatar answered Oct 22 '22 15:10

iouri


Update 2016:

Most upvoted answer still works, but you need to return an empty hash if it's not of the expected type (eg. a PDF that you don't want to process instead of an image), else you'll run into TypeError - can't dup NilClass issues.

Sample using a ternary for terseness:

has_attached_file :file, :styles => lambda { |a| a.instance.is_image? ? {:thumbnail => "320x240!"} : {} }
like image 40
Constant Meiring Avatar answered Oct 22 '22 15:10

Constant Meiring