2011-07-19 40 views
4

我想重命名s3中的很多文件 - 将当前回形针has_attached_file:pathstuff/:id_:updated_at_:style.:extension更改为stuff/:id_:counter_:style.:extension,其中:counter是与图像相同模型中的字段。Rails回形针S3重命名数千个文件?

我还没有关于如何重命名所有文件的模糊 - 最好是在rake任务中。

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

这是Rails 3和最新的Paperclip截至此贴子。

任何想法?

谢谢!

+0

我正在使用aws-s3 gem直接编辑S3存储桶的解决方案。一旦我验证了它的作用,我会在下面发布一个答案......但我认为它会。 :) – wulftone

回答

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 

它只是通过在桶中的所有文件,并根据这个新的模式重新命名他们。我将回形针路径中的计数器字段设置为默认值1,因此新文件名中的_1_

工程就像一个魅力!

1

给回形针的刷新耙任务一试。我用它来生成新的样式,我猜它会在你的路径变化中起作用吗?

https://github.com/thoughtbot/paperclip/wiki/Thumbnail-Generation

+0

我不确定这会起作用 - 我需要重命名原件,而不是缩略图。如果我将:path选项更改为我想要的格式,它当然不会再看到这些文件,所以它将无法使用重新处理对它们进行重命名。 – wulftone