Skip to content

Instantly share code, notes, and snippets.

@yannski
Created April 3, 2009 19:22
Show Gist options
  • Save yannski/89920 to your computer and use it in GitHub Desktop.
Save yannski/89920 to your computer and use it in GitHub Desktop.
require "paperclip_migrations"
class AddPaperclipColumnsToProducts < ActiveRecord::Migration
include PaperclipMigrations
def self.up
add_paperclip_fields :items, :vignette
Product.reset_column_information
Product.all.each do |product|
attachment = Asset.find(:first, :conditions => ["assetable_type = ? and assetable_id = ? and type = ?", "Item", product.id, "Vignette"])
populate_paperclip_from_attachment_fu(product, attachment, 'vignette') if attachment
end
end
def self.down
remove_paperclip_fields :items, :vignette
end
end
module PaperclipMigrations
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def add_paperclip_fields(table, prefix)
add_column table, "#{prefix}_file_name", :string
add_column table, "#{prefix}_content_type", :string
add_column table, "#{prefix}_file_size", :integer
add_column table, "#{prefix}_updated_at", :datetime
end
def remove_paperclip_fields(table, prefix)
remove_column table, "#{prefix}_file_name"
remove_column table, "#{prefix}_content_type"
remove_column table, "#{prefix}_file_size"
remove_column table, "#{prefix}_updated_at"
end
def populate_paperclip_from_attachment_fu(model, attachment, prefix)
unless attachment.filename.nil?
model.send("#{prefix}_file_name=", attachment.filename)
model.send("#{prefix}_content_type=", attachment.content_type)
model.send("#{prefix}_file_size=", attachment.size)
old_path = File.join(RAILS_ROOT, 'public', attachment.public_filename)
new_path = model.send(prefix).path(:original)
new_folder = File.dirname(new_path)
unless File.exists?(new_folder)
FileUtils.mkdir_p(new_folder)
end
if File.exists?(old_path)
puts "Moving #{old_path} to #{new_path}"
File.copy(old_path, new_path)
model.save
model.send(prefix).reprocess!
else
puts "No such file: #{old_path}"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment