2009-07-18

Rake Task to show installed and pending migrations

While developing with Rails I often want to know which migrations are already installed and which are pending. Migrations have names and version numbers. In some rake migration tasks you must specify a migration - but this must be the number :-|

To rest my brain I wrote two rake tasks to show the installed and pending migrations. Feel free to use it for your own - just copy it to a .rake file in your /lib/task directory.


namespace :db do
namespace :migrate do
desc 'Shows installed migrations'
task :installed => :environment do
mt = ActiveRecord::Migrator.new(:up, "db/migrate/")
list = mt.migrations.select{ |mi| mt.migrated.include?(mi.version.to_i) }
print_migration_list(list)
end

desc 'Shows pending migrations'
task :pending => :environment do
mt = ActiveRecord::Migrator.new(:up, "db/migrate/")
print_migration_list(mt.pending_migrations)
end
end
end

def print_migration_list(migrations)
return if migrations.empty?

max_length = migrations.inject(0) {|max, m| [max, m.name.length].max }
puts "Version Name"
puts "---------------" + "-" * max_length
migrations.each do |m|
puts "#{m.version} #{m.name}"
end
end


See also pastie.org

2009-07-14

Generic Cucumber Steps

Zwei generische Steps, die das Ergebnis erster Gehversuche mit Cucumber sind. (Factory = factory_girl)


# Match steps like:
# * And I have projects named A, B, C
Given /^I have .+ named (.+)$/ do |names|
names.split(', ').each do |name|
Factory.create(name)
end
end

# Match steps like:
# * And I should have 1 project
# * And I should have 5 users
Then /^I should have ([0-9]+) (.+)$/ do |count, classes|
Kernel.const_get(classes.singularize.capitalize).count.should == count.to_i
end