简体   繁体   中英

Rails Paperclip S3 rename thousands of files?

I'm trying to rename a lot of files in s3--changing the current paperclip has_attached_file :path from stuff/:id_:updated_at_:style.:extension to stuff/:id_:counter_:style.:extension , where :counter is a field in the same model as the image.

I haven't the foggiest on how to rename all the files--preferably in a rake task.

Incidentally, I'll be incrementing :counter each time a new file is saved to the record.

This is Rails 3 and the latest Paperclip as of this posting.

Any ideas?

Thanks!

Here's my solution:

# 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

It just goes through all the files in the bucket and renames them according to this new schema. I set the:counter field in the Paperclip path to default to 1, thus the _1_ in the new file name.

Works like a charm!

Give paperclip's refresh rake task a try. I've used it to generate new styles and I'm guessing it will pick up on your path change as well?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM