簡體   English   中英

將回形針S3圖像遷移到新的URL /路徑格式

[英]Migrating paperclip S3 images to new url/path format

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

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

我打算在url / path格式中插入:updated_at,並在裁剪期間更新attachment.updated_at,但在實現該更改后,所有現有圖像都需要移動到新位置。 大約有50萬張圖像要重命名為S3。

此時我正在考慮先將它們復制到新位置,然后部署代碼更改,然后移動任何遺漏的圖像(即復制后上傳),但我希望有更簡單的方法...任何建議?

我不得不改變我的回形針路徑以支持圖像裁剪,我最終創建了一個rake任務來幫助我。

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

沒有找到一種可行的方法來遷移到新的url格式。 我最終覆蓋了Paperclip::Attachment#generate_fingerprint因此它附加了:updated_at

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM