namespace :global_shared_db do
namespace :gen do desc '产生migration模板文件: `rake shared_db:gen:create_migration"[migration_name]"`' task :create_migration, [:migration_name] => :environment do |_, args| migration_name = args[:migration_name] abort "migration_name can not be blank!" unless migration_name migration_class_name = migration_name.split('_').map do |chars| chars[0].upcase + chars[1..-1] end.join migration_name = migration_name + '.rb' migration_file_name = [next_migration_number, migration_name].join("_") template = <<-TMP
class #{migration_class_name} < ActiveRecord::Migration
def change end
end TMP
File.open("#{migration_dir}/#{migration_file_name}", 'w+') { |f| f.puts template } end def migration_dir File.expand_path('db/migrate', GlobalSharedDb.root) end def migrations Dir.glob("#{migration_dir}/[0-9]*_*.rb") end def next_migration_number date = Time.now.strftime('%Y%m%d') exist_migrations = migrations.select { |migration| File.basename(migration) =~ /^#{date}/ } next_number = exist_migrations.size + 1 suffix = next_number.to_s.rjust(2, '0') "#{date}#{suffix}" end end # namespace
end