简体   繁体   中英

Rename paperclip files with rake task

I have used in my rails project paperclip to upload some images, by using the default

path: ":class/:attachment/:id_partition/:style/:filename"

So all files are uploaded in an amazon s3 bucket.

Now I want / need to change the filename to

path: ':class/:id/:style/:hash.:extension'

This works well for newly uploaded files, but existing files are not found any more. So I tried to re-use a paperclip rake refresh task. Steps: - Load all attachments with old path, save with new path, delete old entry. This are my results so far:

desc "Move renamed files"
  task :move_renamed_files => :environment do
    klass = Paperclip::Task.obtain_class
    names = Paperclip::Task.obtain_attachments(klass)
    names.each do |name|
      Paperclip.each_instance_with_attachment(klass, name) do |instance|
        attachment = instance.send(name)
        if attachment.exists?
          print "."
        else
          # No hit on new location, trying old location
          org_path = attachment.options[:org_path]
          new_path = attachment.options[:path]
          attachment.options[:path] = org_path
          if attachment.exists?
            # Save file with new name
            puts "#{attachment.url}"
            attachment.options[:path] = new_path
            instance.save(:validate => false)
            # THIS DOES NOT WORK

            #if attachment.save
            #  puts "Save OK"
            #else
            # puts "Save failed"
            #end
          else
              Paperclip::Task.log_error("#{instance.class}##{attachment.name}, #{instance.id}, #{attachment.url}")
          end


        end
      end
    end

Any Ideas how to complete the code? I am absolut stuck in it.

I would dive in to the AWS::S3 library, since you have the paths already. If you know it works then just do it the fast way.

AWS::S3::S3Object.rename(old_name, new_name, 'bucket_name')

Also, this might help: http://blog.magmalabs.io/2015/11/25/rename-s3-assets-after-paperclip-hashing.html

Have created a github working project here:

https://github.com/tclaus/Rename-S3-assets-after-paperclip-hashing

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