Paperclip Renaming Files After They'Re Saved

Paperclip renaming files after they're saved

If, for example, your model has attribute image:

has_attached_file :image, :styles => { ...... }

By default papepclip files are stored in /system/:attachment/:id/:style/:filename.

So, You can accomplish it by renaming every style and then changing image_file_name column in database.

(record.image.styles.keys+[:original]).each do |style|
path = record.image.path(style)
FileUtils.move(path, File.join(File.dirname(path), new_file_name))
end

record.image_file_name = new_file_name
record.save

Paperclip - rename file before saving

This is the way how I fix my issue:

  def rename_avatar
#avatar_file_name - important is the first word - avatar - depends on your column in DB table
extension = File.extname(avatar_file_name).downcase
self.avatar.instance_write :file_name, "#{Time.now.to_i.to_s}#{extension}"
end

Rails Paperclip S3 rename thousands of files?

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!

How can I change image file names with Paperclip when already in production

You can try this. Lets say your model is Avatar.

  1. Create a copy of your model, say OldAvatar. Set table name in this model to 'avatars'
  2. In Avatar model, set the paperclip path/filename as you want it to be.
  3. Now you can write a rake task which will loop through each OldAvatars and create new Avatars using the OldAvatar image file

Note: You have to delete the OldAvatars in the loop, and probably save necessary fields like user_id, etc..

Rename paperclip files with rake task

Have created a github working project here:

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



Related Topics



Leave a reply



Submit