Rails Paperclip S3重命名成千上万的文件?

wul*_*one 4 rename ruby-on-rails amazon-s3 paperclip

我试图重新命名了很多文件在S3 -改变当前回形针has_attached_file :pathstuff/:id_:updated_at_:style.:extensionstuff/:id_:counter_:style.:extension,那里:counter是在同一个模型作为图像的领域.

我对如何重命名所有文件并不是最模糊的 - 最好是在rake任务中.

顺便说一句,:counter每次将新文件保存到记录时,我都会递增.

这是Rails 3和最新的Paperclip.

有任何想法吗?

谢谢!

wul*_*one 5

这是我的解决方案:

# This task changes all of the keys from the current format,
# :id_:image_updated_at_:style, to :id_:image_counter_:style.
# :image_counter is set arbitrarily at 1, since all records have
# a default of 1 in that field (until they're updated).
desc "One-time renaming of all the amazon s3 content for User.image"

task :rename_s3_files, [:bucket] => :environment do |t, args|
  require 'aws/s3'

  cred = YAML.load(File.open("#{Rails.root}/config/s3.yml")).symbolize_keys!
  AWS::S3::Base.establish_connection! cred

  bucket = AWS::S3::Bucket.find(args[:bucket])

  # Rename everything in the bucket, taking out the timestamp and replacing it with "1"
  bucket.each do |obj|
    arr = obj.key.split('_')
    obj.rename(arr[0] + '_1_' + arr[2])
  end

end
Run Code Online (Sandbox Code Playgroud)

它只是遍历存储桶中的所有文件,并根据此新架构重命名它们.我在Paperclip路径中将:counter字段设置为默认值为1,因此_1_在新文件名中.

奇迹般有效!