将回形针S3图像迁移到新的URL /路径格式

时间:2012-01-16 01:57:03

标签: ruby-on-rails ruby-on-rails-3.1 amazon-s3 paperclip

是否有推荐的技术将大量回形针S3图像迁移到新的:url和:路径格式?

原因是因为在升级到rails 3.1之后,裁剪后没有显示新版本的拇指(显示以前缓存的版本)。这是因为文件名不再更改(因为在rails 3.1中删除了asset_timestamp)。我正在使用:url / path格式的指纹,但这是从原始生成的,在裁剪时不会改变。

我打算以url / path格式插入:updated_at,并在裁剪期间更新attachment.updated_at,但在实施该更改后,所有现有图像都需要移动到新位置。大约有50万张图像要重命名为S3。

此时我正在考虑首先将它们复制到新位置,然后部署代码更改,然后移动任何错过的图像(即复制后上传),但我希望有更简单的方法..任何建议?

2 个答案:

答案 0 :(得分:6)

我必须更改回形针路径以支持图像裁剪,最后我创建了一个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

答案 1 :(得分:2)

未找到迁移到新网址格式的可行方法。我最终覆盖了Paperclip::Attachment#generate_fingerprint,因此它附加了:updated_at