Skip to content

Instantly share code, notes, and snippets.

@warp
Forked from jystewart/paperclip_migrations.rb
Created July 22, 2011 08:13
Show Gist options
  • Save warp/1099070 to your computer and use it in GitHub Desktop.
Save warp/1099070 to your computer and use it in GitHub Desktop.
Migration from attachment_fu database storage to paperclip
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_attachment_fu_fields(table)
remove_column table, :filename
remove_column table, :content_type
remove_column table, :size
remove_column table, :db_file_id
end
def populate_paperclip_from_attachment_fu(model, prefix)
Object.const_set(:DbFile, Class.new(ActiveRecord::Base)) unless Object.const_defined?(:DbFile)
model.class.belongs_to :db_file, :class_name => '::DbFile', :foreign_key => 'db_file_id' unless model.respond_to?(:db_file)
unless model.filename.nil?
model.send("#{prefix}_file_name=", model.filename)
model.send("#{prefix}_content_type=", model.content_type)
model.send("#{prefix}_file_size=", model.size)
model.save
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 model.db_file
puts "Writing to #{new_path}"
File.open(new_path, 'w') { |f| f.puts model.db_file.data }
model.send(prefix).reprocess!
else
puts "No data for: #{model.inspect}"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment