2012-01-16 61 views
4

是否有將大量回形針S3圖像遷移到新的url:路徑格式的推薦技術?將回形針S3圖像遷移到新的url /路徑格式

原因是因爲在升級到rails 3.1之後,裁剪後沒有顯示新版本的拇指(以前顯示緩存的版本)。這是因爲文件名不再更改(因爲rails 3.1中刪除了asset_timestamp)。我使用的是:URL /路徑格式的指紋,但是這是從原始生成的,在裁剪時不會更改。

我打算在url /路徑格式中插入:updated_at,並在裁剪過程中更新attachment.updated_at,但在實現該更改後,所有現有圖像都需要移至其新位置。這大約有50萬張圖片需要重新命名爲S3。

在這一點上,我正在考慮首先將它們複製到新的位置,然後部署代碼更改,然後移動任何錯過的圖像(即在複製後上傳),但我希望有一種更簡單的方法。 .. 有什麼建議麼?

回答

2

未找到遷移到新的url格式的可行方法。我最終壓倒Paperclip::Attachment#generate_fingerprint,所以它附加:updated_at

5

爲了支持圖像裁剪,我不得不改變我的回形針路徑,最後我創建了一個rake task來幫忙。

namespace :paperclip_migration do 

    desc 'Migrate data' 
    task :migrate_s3 => :environment do 
    # Make sure that all of the models have been loaded so any attachments are registered 
    puts 'Loading models...' 
    Dir[Rails.root.join('app', 'models', '**/*')].each { |file| File.basename(file, '.rb').camelize.constantize } 

    # Iterate through all of the registered attachments 
    puts 'Migrating attachments...' 
    attachment_registry.each_definition do |klass, name, options| 
     puts "Migrating #{klass}: #{name}" 
     klass.find_each(batch_size: 100) do |instance| 
     attachment = instance.send(name) 

     unless attachment.blank? 
      attachment.styles.each do |style_name, style| 
      old_path = interpolator.interpolate(old_path_option, attachment, style_name) 
      new_path = interpolator.interpolate(new_path_option, attachment, style_name) 
      # puts "#{style_name}:\n\told: #{old_path}\n\tnew: #{new_path}" 
      s3_copy(s3_bucket, old_path, new_path) 
      end 
     end 
     end 
    end 

    puts 'Completed migration.' 
    end 

    ############################################################################# 
    private 

    # Paperclip Configuration 
    def attachment_registry 
    Paperclip::AttachmentRegistry 
    end 

    def s3_bucket 
    ENV['S3_BUCKET'] 
    end 

    def old_path_option 
    ':class/:id_partition/:attachment/:hash.:extension' 
    end 

    def new_path_option 
    ':class/:attachment/:id_partition/:style/:filename' 
    end 

    def interpolator 
    Paperclip::Interpolations 
    end 

    # S3 
    def s3 
    AWS::S3.new(access_key_id: ENV['S3_KEY'], secret_access_key: ENV['S3_SECRET']) 
    end 

    def s3_copy(bucket, source, destination) 
    source_object = s3.buckets[bucket].objects[source] 
    destination_object = source_object.copy_to(destination, {metadata: source_object.metadata.to_h}) 
    destination_object.acl = source_object.acl 
    puts "Copied #{source}" 
    rescue Exception => e 
    puts "*Unable to copy #{source} - #{e.message}" 
    end 

end 
+0

嗨@jessecurry,這是證明工作嗎?不管我的路是什麼?它也保存了分貝? – Hamdan 2016-04-13 05:37:00

+0

@Hamdan當時爲我工作,您需要確保新舊路徑選項對您的配置是正確的。 – jessecurry 2016-05-05 03:52:50