2014-02-18 27 views
1

我想轉換一個上傳的文本文件附件在rails中使用回形針處理器的行。我可以使用調試器驗證我的處理器是否被調用,但是附加的文件是我的原始文件,而不是處理器寫入的文件。這裏是我的處理器:回形針處理器不改變文件內容

module Paperclip 
    class Utf8 < Processor 
    def initialize(file, options={}, attachment=nil) 
     super 
     @file   = file 
     @attachment  = attachment 
     @current_format = File.extname(@file.path) 
     @format   = options[:format] 
     @basename  = File.basename(@file.path, @current_format) 
    end 

    def make 
     @file.rewind 
     tmp = Tempfile.new([@basename, @format]) 

     IO.foreach(@file.path) do |line| 
     tmp << line.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '') 
     end 

     tmp.flush 
     tmp 
    end 
    end 
end 

,這裏是我的模型:

class List < ActiveRecord::Base 
    has_attached_file :file, 
        storage: :s3, 
        s3_credentials: Rails.root.join('config', 'aws.yml'), 
        bucket: Rails.application.config.s3_bucket, 
        processors: [:utf8], 
        styles: { 
         utf8: { 
          format: 'txt' 
         } 
        } 
end 

任何想法,我做錯了嗎?據我瞭解,從make返回的文件是paperclip附加到模型的文件。可能s3與此有關?

+0

也許這不是你的情況,但什麼回形針一般不會是原來的文件名存儲在數據庫中,並且根據您定義的轉換,在文件系統上存儲不同的版本。原來加上轉換。 因此,作爲附件得到的東西很大程度上取決於您如何將其發送到瀏覽器。在你的情況下,你可能需要告訴你的控制器如何發送你的文件。 –

+0

啊,我現在明白了。每個處理器保存文件的新版本。我將如何讓控​​制器發送不同的樣式? – mockaroodev

回答

1

找到了一個解決辦法:回形針保存每個樣式是作爲一個單獨的文件。要覆蓋而不是創建一個新的原始文件,我有我的模式改變爲:

class List < ActiveRecord::Base 
    has_attached_file :file, 
        storage: :s3, 
        s3_credentials: Rails.root.join('config', 'aws.yml'), 
        bucket: Rails.application.config.s3_bucket, 
        processors: [:utf8], 
        styles: { 
         original: { # specifying original style here causes the original file to be overwritten 
          format: 'txt' 
         } 
        } 
end