简体   繁体   English

使用rake任务重命名回形针文件

[英]Rename paperclip files with rake task

I have used in my rails project paperclip to upload some images, by using the default 我已经在Rails项目的回形针中使用默认值上传了一些图像

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

So all files are uploaded in an amazon s3 bucket. 因此,所有文件都将上载到amazon s3存储桶中。

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. 由于您已经拥有路径,因此我将深入研究AWS :: S3库。 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 另外,这可能会有所帮助: http : //blog.magmalabs.io/2015/11/25/rename-s3-assets-after-paperclip-hashing.html

Have created a github working project here: 在这里创建了一个github工作项目:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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