Working on a migration recently I noticed the same set of operations being done repeatedly. My first reaction was to DRY up the code by creating a utility method, within the migration. But I was sure I’d end up needing this method in future migrations. But the question was, where should I put it?
The answer was to create a migration helper!
First, I created lib/migration_help.rb containing the following:
module MigrationHelper
def do_good_stuff()
say "boy, this method will be useful..."
end
def undo_good_stuff()
say "actually on second thoughts it was stupid..."
end
end
Then in my migration I added 'require' and 'extend' to import the MigrationHelper module.
require "migration_helper"
class AddNewFeatureColumns < ActiveRecord::Migration
extend MigrationHelper
def self.up
do_good_stuff
end
def self.down
undo_good_stuff
end
end
And that was it! The helper method names have been changed, to protect the innocent, but you get the idea. Not exactly rocket science but usefully if you need to condense your migrations.
For more information I suggest you check out the excellent discussion on migrations, in the RailsGuides; after reading it I changed all my migration helper 'puts' statements to 'say' statements. It nice to get those little details right.
© Copyright 2009-2012 Peer Assembly | All Rights Reserved.
Post Comments