Created
March 7, 2016 18:26
-
-
Save 121onto/acc588b859893ddacebf to your computer and use it in GitHub Desktop.
Example migration for changing paperclip storage path
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 MoveAttachmentsToNewLocation < ActiveRecord::Migration | |
def initialize(name = self.class.name, version = nil) | |
access_key = Rails.application.secrets.g3_access_key_id | |
secret_key = Rails.application.secrets.g3_secret_access_key | |
storage = Fog::Storage::Google.new google_storage_access_key_id: access_key, | |
google_storage_secret_access_key: secret_key | |
@bucket_name = Rails.application.secrets.g3_bucket | |
@bucket = storage.directories.get(@bucket_name) | |
super(name, version) | |
end | |
def copy_helper(attachment, style) | |
old_path = Paperclip::Interpolations.interpolate(@original_path_string, attachment, style) | |
new_path = Paperclip::Interpolations.interpolate(@new_path_string, attachment, style) | |
file = @bucket.files.get(old_path) | |
return unless !file.nil? | |
copy = file.copy(@bucket_name, new_path) | |
copy.public = true | |
copy.save | |
file.destroy | |
end | |
def up | |
@original_path_string = ":class/:attachment/:id_partition/:style/:filename" | |
@new_path_string = "my/new/path/:filename.:extension" | |
# model_with_attachemnt | |
items = ModelWithAttachment.all | |
items.each do |item| | |
styles = [:medium] | |
styles.each do |style| | |
attachments = [item.avatar] | |
attachments.each do |attachment| | |
copy_helper(attachment, style) | |
end | |
end | |
end | |
# other_model_with_attachments | |
items = OtherModelWithAttachments.all | |
items.each do |item| | |
styles = [:medium, :thumb] | |
styles.each do |style| | |
attachments = [item.avatar, item.image] | |
attachments.each do |attachment| | |
copy_helper(attachment, style) | |
end | |
end | |
end | |
end | |
def down | |
@original_path_string = "my/new/path/:filename.:extension" | |
@new_path_string = ":class/:attachment/:id_partition/:style/:filename" | |
# model_with_attachemnt | |
items = ModelWithAttachment.all | |
items.each do |item| | |
styles = [:medium] | |
styles.each do |style| | |
attachments = [item.avatar] | |
attachments.each do |attachment| | |
copy_helper(attachment, style) | |
end | |
end | |
end | |
# other_model_with_attachments | |
items = OtherModelWithAttachments.all | |
items.each do |item| | |
styles = [:medium, :thumb] | |
styles.each do |style| | |
attachments = [item.avatar, item.image] | |
attachments.each do |attachment| | |
copy_helper(attachment, style) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
return unless !file.nil? -> return if file.nil?