/ Published in: Ruby
Add a method to ActiveRecord::Migration to automatically drop created tables/indexes within the current migration file.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
module AutoDropMigration module Migration # Drop all tables and indexes created by the migration # class AddUser < ActiveRecord::Migration # def self.up # ... # end # # def self.down # drop_created_tables_and_indexes(__FILE__) # end # def drop_created_tables_and_indexes(migration) File.open(migration) do |fp| fp.readlines.reverse.each do |line| if line =~ /^\s+add_index\s+(.*)$/ args = eval("parse_args(#{$1})") eval("remove_index #{args[0..1].join(',')}") rescue nil elsif line =~ /^\s+add_foreign_key\s+(.*)$/ eval("remove_foreign_key #{$1}") rescue nil elsif line =~ /^\s+create_table\s+:([^,]+)(,.*)$/ drop_table($1) rescue nil end end end end def parse_args(*s) s end end end ActiveRecord::Migration.extend(AutoDropMigration::Migration)