# Add Downs require 'activerecord' module BackwardsString def <<(str) replace(str + "\n" + self) end end class ActiveRecord::Migration def self.inherited(c) class << c attr_reader :text def create_table(table_name, *options) @text << " drop_table :#{table_name}" end def rename_table(old_name, new_name) @text << " rename_table :#{new_name}, :#{old_name}" end def add_column(table_name, column_name, *args) @text << " remove_column :#{table_name}, :#{column_name}" end def rename_column(table_name, old_name, new_name) @text << " rename_column :#{table_name}, :#{new_name}, :#{old_name}" end def change_column(table_name, column_name, *args) @text << " change_column :#{table_name}, :#{column_name}, UNKNOWN COLUMN TYPE!" end def remove_column(table_name, column_name) @text << " add_column :#{table_name}, :#{column_name}, UNKNOWN COLUMN TYPE!" end def add_index(table_name, column_names, options = {}) index_name = options[:name] if index_name @text << " remove_index :#{table_name}, :name => :#{index_name}" else @text << " remove_index :#{table_name}, :column => #{column_names.inspect}" end end def singleton_method_added(m) if m == :down @text = "".extend(BackwardsString) up @text = " def down\n" + @text + " end\nend\n" end end end end end class DownAdder def self.tempfile(file) RAILS_ROOT + "/tmp/migrations/" + File.basename(file) end def self.create_tmp_dir Dir.mkdir(RAILS_ROOT + "/tmp/migrations/") rescue Errno::EEXIST end def self.add_down(migration) create_tmp_dir File.open(tempfile(migration),"w") do |temp| File.open(migration) do |fh| while line = fh.gets if line =~ /def self\.down/ load migration b = File.basename(migration)[4..-4] c = Object.const_get(b.camelize) temp.puts(c.text) break else temp.puts(line) end end end end end end