Created
September 17, 2008 00:53
-
-
Save lifo/11172 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Released under WTFPL - http://sam.zoy.org/wtfpl/ | |
module PoorMansMigrations | |
def self.extended(base) | |
base.class_inheritable_accessor :migration_columns | |
base.migration_columns = [] | |
end | |
def column(name, type, options = {}) | |
self.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? | |
self.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 - self.migration_columns.map {|m| m[:column_name].to_s} - Array(primary_key) | |
connection.remove_columns(table_name, left_overs) | |
reset_column_information | |
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