Skip to content

Instantly share code, notes, and snippets.

@stevegrossi
Created December 21, 2013 14:43
Show Gist options
  • Save stevegrossi/8070232 to your computer and use it in GitHub Desktop.
Save stevegrossi/8070232 to your computer and use it in GitHub Desktop.
How to rename a Paperclip attachment when an interpolated attribute in the Filename changes
class Image < ActiveRecord::Base
attr_accessible :custom_file_name
has_attached_file :attachment
after_save :rename_attached_file, if: :rename_necessary?
def rename_attached_file
(attachment.styles.keys).each do |style|
new_path = attachment.path(style)
old_path = new_path.gsub("attachments/#{custom_file_name}", "attachments/#{custom_file_name_was}")
rename_attachment(attachment, old_path, new_path)
end
end
private
def rename_necessary?
custom_file_name_changed? && !attachment_updated_at_changed?
end
def rename_attachment(attachment, old_path, new_path)
case attachment.options[:storage]
when :filesystem
File.rename(old_path, new_path)
when :s3
attachment.s3_bucket.objects[old_path].move_to(new_path, acl: :public_read)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment