Sha256: 9e3350d2c0335a4265f3eb058aacba8f5d696f6029b977de9e3199bc9f93d0e5

Contents?: true

Size: 1.15 KB

Versions: 2

Compression:

Stored size: 1.15 KB

Contents

require "activerecord"
require "fast_change_table/version"

module FastChangeTable
  def self.included(base)
    base.extend ClassMethods
  end
  
  module ClassMethods
    def fast_change_table(table_name, &block)
      old_table_name = "old_#{table_name}"
      rename_table table_name, old_table_name 
      begin
         execute "DROP TABLE IF EXISTS #{table_name}" 
         execute "CREATE TABLE #{table_name} LIKE #{old_table_name}" 
         change_table(table_name, &block)
         #prepare the columns names for the insert statements
         old = connection.columns(old_table_name).collect(&:name)
         current = connection.columns(table_name).collect(&:name)
         common = (current & old).sort
         columns_to_s = common.collect {|c| "`#{c}`"}.join(',')
         execute "INSERT INTO #{table_name}(#{columns_to_s}) SELECT #{columns_to_s} FROM #{old_table_name}" 
         drop_table old_table_name
      rescue Exception => e
         puts "#{e}\n#{e.backtrace}"
         execute "DROP TABLE IF EXISTS #{table_name}"
         rename_table old_table_name, table_name
      end
    end
  end
end

::ActiveRecord::Migration.send :include, FastChangeTable

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
fast_change_table-0.0.2 lib/fast_change_table.rb
fast_change_table-0.0.1 lib/fast_change_table.rb