2014-04-18 47 views
4

如何使用單個回形針字段來處理不同的文件類型。例如,我有與說回形針方法的文件模型:如何使用回形針處理多種文件類型

has_attached_file :file 

此文件可以是圖片,音頻,視頻或文檔。

如果它是一個圖片,我怎樣才能使它使得has_attached_file :file將能夠處理這樣的圖片:

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

然後,如果是其它類型的文檔,它只是工作正常,而不樣式,所以我不必爲不同的文件類型創建字段。

+1

爲什麼downvote?這是一個合法的問題! –

回答

5

您將處理條件樣式的方式是使用lambda來確定您正在處理的內容類型。我們以前使用Rails /回形針的早期版本中做到了這一點:

#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 
+0

驗證不是問題,我想要的是當它的圖像內容類型時,我希望它爲圖像生成不同的樣式。 – Uchenna

+0

對不起,我誤解了這個問題。讓我爲你解決這個問題! –

+0

爲您更新了先生的答案! –

3

得益於豐富的派克的答案,我能解決我的問題與此解決方案。

首先使用拉姆達的處理條件

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

然後我在這個方法中,我做了驗證定義check_file_type

命名的自定義方法,並在此基礎上ruby best pratice article

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?以處理視頻和ima水電站。

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/] 

用這種方法,我現在可以用一個曲別針的方法來處理多種文件類型。

相關問題