2011-11-09 47 views
2

我在Rails 3上使用Paperclip(w/Amazon s3)。我想將一個新文件附加到我的模型中,而不替換舊文件。我不希望舊文件可以訪問,我只想在s3上作爲備份。 你知道是否有辦法告訴回形針照顧它嗎?PaperClip - 保存新的附件而不刪除舊的附件

在post.rb

我:

has_attached_file :sound, 
     :storage => :s3, 
     :s3_credentials => "....", 
     :styles => {:mp3 => {:format => :mp3}}, 
     :processors => [:sound_processor], 
     :s3_host_alias => '....', 
     :bucket => '....', 
     :path => ":attachment/:id/:style/out.:extension", 
     :url => ":s3_alias_url" 

和處理器如下:

class Paperclip::SoundProcessor < Paperclip::Processor 

    def initialize file, options = {}, attachment = nil 
    super 

    @format = options[:format] || "mp3" 
    @current_format = File.extname(@file.path) 
    @basename = File.basename(@file.path, @current_format) 
    end 

    def make 
    src = @file 
    dst = Tempfile.new([@basename,".#{@format}"]) 
    dst.binmode 

    cmd = "ffmpeg -y -ab 128k -t 600 -i #{File.expand_path(src.path)} #{File.expand_path(dst.path)}" 
    Paperclip.log(cmd) 
    out = `#{cmd}` 
    raise Paperclip::PaperclipError, "processor does not accept the given audio file" unless $?.exitstatus == 0 

    dst 
    end 

end 

回答

4

這是我做的。我在保存文件名之前給它加上時間戳(以防止另一個同名文件覆蓋原始文件),並強制回形針永不刪除任何內容。

before_create :timestamp_filename 

def timestamp_filename 
    fname = Time.now.to_s(:db).gsub(/[^0-9]/,'') + '_' + sound_file_name 
    sound.instance_write(:file_name, fname) 
end 

# override paperclip's destroy files 
# method to always keep them around 
def destroy_attached_files 
    true 
end 
0

這是相當直接的版本中組合添加到您的機型,近日筆者用戶CarrierWave和paper_trail實現這一目標。我們正在部署到Heroku,所以S3也在混合中。

我發佈這個作爲答案的原因是,雖然有爭議,但我不認爲PaperClip這樣的圖書館應該支持備份文件,但爲了解決這個問題,特定的庫對我個人而言更好。