Posted By


ctran on 08/21/06

Tagged


Statistics


Viewed 572 times
Favorited by 1 user(s)

auto_drop_migration.rb


/ Published in: Ruby
Save to your folder(s)

Add a method to ActiveRecord::Migration to automatically drop created tables/indexes within the current migration file.


Copy this code and paste it in your HTML
  1. module AutoDropMigration
  2. module Migration
  3. # Drop all tables and indexes created by the migration
  4. # class AddUser < ActiveRecord::Migration
  5. # def self.up
  6. # ...
  7. # end
  8. #
  9. # def self.down
  10. # drop_created_tables_and_indexes(__FILE__)
  11. # end
  12. #
  13. def drop_created_tables_and_indexes(migration)
  14. File.open(migration) do |fp|
  15. fp.readlines.reverse.each do |line|
  16. if line =~ /^\s+add_index\s+(.*)$/
  17. args = eval("parse_args(#{$1})")
  18. eval("remove_index #{args[0..1].join(',')}") rescue nil
  19. elsif line =~ /^\s+add_foreign_key\s+(.*)$/
  20. eval("remove_foreign_key #{$1}") rescue nil
  21. elsif line =~ /^\s+create_table\s+:([^,]+)(,.*)$/
  22. drop_table($1) rescue nil
  23. end
  24. end
  25. end
  26. end
  27.  
  28. def parse_args(*s)
  29. s
  30. end
  31. end
  32. end
  33.  
  34. ActiveRecord::Migration.extend(AutoDropMigration::Migration)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.