Created
December 21, 2013 14:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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