如何使用paperclip处理多种文件类型

Uch*_*nna 5 ruby-on-rails paperclip ruby-on-rails-3 ruby-on-rails-4

如何使用单个回形针字段来处理不同的文件类型.例如,我有一个带有回形针方法的文件模型,该方法说:

has_attached_file :file
Run Code Online (Sandbox Code Playgroud)

此文件可以是图片,音频,视频或文档.

如果它是一张图片,我怎样才能使它has_attached_file :file能够以这种方式处理图片:

has_attached_file :file, styles: {thumb: "72x72#"}
Run Code Online (Sandbox Code Playgroud)

然后,如果它是其他文档类型,它将在没有样式的情况下正常工作,因此我不必为不同的文件类型创建字段.

Ric*_*eck 6

处理条件样式的方法是使用a 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
Run Code Online (Sandbox Code Playgroud)