Manish
Manish

Reputation: 261

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.

Upvotes: 7

Views: 2521

Answers (2)

Constant Meiring
Constant Meiring

Reputation: 3335

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!"} : {} }

Upvotes: 3

iouri
iouri

Reputation: 2929

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

Upvotes: 6

Related Questions