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.

1 answer