Skip to content

Instantly share code, notes, and snippets.

@levent
Forked from lifo/gist:11172
Created September 18, 2008 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save levent/11439 to your computer and use it in GitHub Desktop.
Save levent/11439 to your computer and use it in GitHub Desktop.
# Released under WTFPL - http://sam.zoy.org/wtfpl/
module PoorMansMigrations
@@_migration_columns = []
def column(name, type, options = {})
@@_migration_columns << {:column_name => name, :column_type => type, :options => options}
end
def realize!(force_drop = false)
# Force drop if needed
connection.drop_table(table_name) if force_drop && table_exists?
# Create table
connection.create_table(table_name) {|t| } unless table_exists?
@@_migration_columns.each do |p|
#haxhaxhax - Force reload reading column names. Whatever.
reset_column_information
column_exists = column_names.include?(p[:column_name].to_s)
# Delete the columns if forced to
if p[:options].delete(:force) && column_exists
connection.remove_columns(table_name, p[:column_name])
column_exists = false
end
connection.add_column(table_name, p[:column_name], p[:column_type], p[:options]) unless column_exists
end
end
def clean_leftover_columns!
return unless table_exists?
reset_column_information
left_overs = column_names - @@_migration_columns.map {|m| m[:column_name].to_s} - Array(primary_key)
connection.remove_columns(table_name, left_overs)
end
# Force recreation for everything
def migrate!
realize!(true)
clean_leftover_columns!
end
# Take it easy. Only force if specified in column definition
def migrate
realize!
clean_leftover_columns!
end
end
ActiveRecord::Base.send :extend, PoorMansMigrations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment