How to use paperclip to process multiple file types

How much is it possible to use one separate clip field for processing for different types of files. For example, I have a file model with a paperclip method that states:

has_attached_file :file

This file can be an image, audio, video or document.

If this is an image, how can I make it so that I has_attached_file :filecan process the images this way:

has_attached_file :file, styles: {thumb: "72x72#"}

Then, if these are other types of documents, it will work as usual without style, so I do not need to create fields for different types of files.

+4
source share
2 answers

, lambda, , . 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
+5

Rich Peck Answer, .

  has_attached_file :file,
                    styles: lambda { |a| a.instance.check_file_type}

check_file_type

Ruby best pratice

def check_file_type
    if is_image_type?
      {:small => "x200>", :medium => "x300>", :large => "x400>"}
    elsif is_video_type?
      {
          :thumb => { :geometry => "100x100#", :format => 'jpg', :time => 10, :processors => [:ffmpeg] },
          :medium => {:geometry => "250x150#", :format => 'jpg', :time => 10, :processors => [:ffmpeg]}
      }
    else
      {}
    end
  end

is_image_type? is_video_type? , .

  def is_image_type?
    file_content_type =~ %r(image)
  end

  def is_video_type?
    file_content_type =~ %r(video)
  end

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

, paperclip .

+3

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


All Articles