More Verbose Migrations

Migrations are a simple way of manipulating a database schema using pure Ruby. Rails migrations aren't tied to a specific database, which makes them very powerful. The same migrations and schema can be applied to MySQL, SQLite, Oracle, and a number of other databases.

This post is aimed at those who are already familiar with migrations and just want to add a bit of spice to them. I'm only writing about two simple methods that can make migrations a little more verbose. When rake db:migrate is called, it prints out more or less what is happening (tables or columns being manipulated). If you're running a migration that for instance cleans up records, Rails won't offer much information other than the migration's class name.

The first method is say_with_time(message). Here's a sample usage snippet.

say_with_time "Populating published_at column..." do
  # Sprinkle magic dust here
end

This will simple print the time elapsed since you ran the migration script and the provided message before executing the code inside the block.

Second, say(message, subitem = false). It basically does the same as the first method, prints a message to the console, but with the added bonus of the subitem option. The subitem option just indents the output, so it looks like it's part of the parent migration.

say "Adding default user to database...", true
# Sprinkle magic dust here

This would print the message indented in the console. Of course with the addition of a database seed file in Rails, putting default data in a migration is no longer needed.

Now, let's bring these fantastic methods together in one example.

say_with_time "Destroying users with nil account_id..." do
  if user.account_id.nil?
    say "Destroying user #{user.id}", true
    user.destroy
  end
end

Filed in Programming and Tutorials.