How to use paperclip to handle multiple file types

paperclip, ruby-on-rails, ruby-on-rails-3, ruby-on-rails-4

Solution

The way you'll handle conditional styling is to use a `lambda` to determine what type of content you're dealing with. We've done this before with an earlier version of Rails / Paperclip:

#app/models/attachment.rb
Class Attachment < ActiveRecord::Base
    has_attached_file :file,
    styles: lambda { |a| a.instance.is_image? ? {:small => "x200>", :medium => "x300>", :large => "x400>"} : {}}  

    validates_attachment_content_type :file, :content_type => [/\Aimage\/.*\Z/, /\Avideo\/.*\Z/]

    private

    def is_image?
        attachment.instance.attachment_content_type =~ %r(image)
    end
end

Problem

How possible is it to use one single paperclip field to handle for different file types. For example, I have a file model with with a paperclip method that says: ``` has_attached_file :file ``` This file can be a picture, audio, video, or document. If it's a picture, how can I make it such that the `has_attached_file :file` would be able to handle pictures in this way: ``` has_attached_file :file, styles: {thumb: "72x72#"} ``` Then if it's other document types, it would work just as normal without the style so I don't have to create fields for different file types.

Original source

Related problems