module Rails::Generators module MigrationHelper include Rails::Generators::Migration include Rails::Generators::BasicHelper module ClassMethods def migration_lookup_at(dirname) #:nodoc: Dir.glob("#{dirname}/[0-9]*_*.rb") end def migration_exists?(dirname, file_name) #:nodoc: migration_lookup_at(dirname).grep(/\d+_#{file_name}.rb$/).first end alias_method :first_migration_file, :migration_exists? def latest_migration_file(dirname, file_name) #:nodoc: migration_lookup_at(dirname).grep(/\d+_#{file_name}.rb$/).sort.last end def current_migration_number(dirname) #:nodoc: migration_lookup_at(dirname).collect do |file| File.basename(file).split("_").first.to_i end.max.to_i end def next_migration_number(dirname) #:nodoc: orm = Rails.configuration.generators.options[:rails][:orm] require "rails/generators/#{orm}" "#{orm.to_s.camelize}::Generators::Base".constantize.next_migration_number(dirname) rescue raise NotImplementedError end end def self.included(base) #:nodoc: base.extend ClassMethods end def reverse_migration! migration_path reverse_migration_path = migration_path.gsub /^add_/, 'remove_' reverse_migration_path = migration_path.gsub /^create_/, 'drop_' FileUtils.mv(migration_path, reverse_migration_path) if migration_path != reverse_migration_path file = File.new(reverse_migration_path) # Change class name gsub_file reverse_migration_path, /class Add/, 'class Remove' gsub_file reverse_migration_path, /class Create/, 'class Drop' # swap up and down methods gsub_file reverse_migration_path, /up/, 'dwn' gsub_file reverse_migration_path, /down/, 'up' gsub_file reverse_migration_path, /dwn/, 'down' end def latest_migration_file dir, name self.class.latest_migration_file dir, name end def migration(options) migration_template "create_users.erb", "db/migrations/#{name}" end end end