Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styles in Paperclip only if it's an image [rails]

I'm using paperclip to upload all sorts of files (text documents, binaries, images).

I'd like to put this in my model:

has_attached_file :attachment, :styles => { :medium => "300x300>", :thumb => "100x100>" }

but it has to perform the styles only if it's an image. I tried adding

if :attachment_content_type =~ /^image/

but it didn't work.

like image 873
Steven Fauconnier Avatar asked May 27 '10 09:05

Steven Fauconnier


2 Answers

You can use before_<attachment>_post_process callback to halt thumbnail generation for non-images. If you return false in callback, there will be no attempts to use styles.

See "Events" section in docs

  before_attachment_post_process :allow_only_images

  def allow_only_images
    if !(attachment.content_type =~ %r{^(image|(x-)?application)/(x-png|pjpeg|jpeg|jpg|png|gif)$})
      return false 
    end
  end 
like image 135
Voyta Avatar answered Sep 21 '22 19:09

Voyta


May be you need something like this:

:styles => lambda { |attachment| 
    !attachment.instance.image? ? {} : {:thumb => "80x24", :preview => "800x600>"} 
}

And define method in your model:

def image?
   attachment.content_type.index("image/") == 0
end
like image 21
KIR Avatar answered Sep 23 '22 19:09

KIR