Return to Snippet

Revision: 910
at September 15, 2006 15:31 by ctran


Updated Code
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)

Revision: 909
at August 21, 2006 00:25 by ctran


Initial Code
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+create_table\s+:([^,]+)(,.*)$/
            drop_table($1)
          elsif line =~ /^\s+add_foreign_key\s+(.*)$/
            remove_foreign_key(*(parse_args($1)))
          elsif line =~ /^\s+add_index\s+(.*)$/
          end
        end
      end
    end
    
    def parse_args(args) 
      args.split(',').map { |e| e.strip!; e.delete!(':'); e }
    end
  end
end

Initial URL


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

Initial Title
auto_drop_migration.rb

Initial Tags
rails

Initial Language
Ruby