Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aitor/85caf1d6f6a972592779c94d48198a7f to your computer and use it in GitHub Desktop.
Save aitor/85caf1d6f6a972592779c94d48198a7f to your computer and use it in GitHub Desktop.
Example migration for changing paperclip storage path
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