zerosum dirt(nap)

evolution through a series of accidents

zerosum dirt(nap)

Rake: Ant Be Gone!

April 02, 2007 by nap · Comments

I spent the better part of my morning today writing some code to do sample data generation within the framework we’re building. I’d originally packaged it as a standalone utility class to be run with the script/runner facility until I realized that it was a perfect candidate for a custom Rake task. And a perfect topic for a blog entry — two for the win!

If you’ve never written a Rake task before and are a Ruby pseudo-noob, fear not. If you’ve written Ant or Make scripts before, and have the requisite passing familiarity with Ruby, it’ll be old hat. Of course, the big win with Rake is that you get to write your tasks in Ruby. Sweet, sweet Ruby. No crufty XML here.

What follows is pretty minimalist, but I wanted to record it for posterity. Also, many of the tutorials I looked at didn’t deal with handling parameters, so I figured it might be useful to someone else out there…

namespace :foo do
  desc "Generate sample data for the app"
  task :sample_data => [:environment] do |t|
    require 'db/script/sample_data.rb'

    num_users = ENV.include?('NUM_USERS') ? ENV['NUM_USERS'] : 5
    SampleData.generate(num_users.to_i)
  end
end

What we’re doing here is defining a task named sample_data within the foo namespace. We declare a dependency on the Rails :environment, which is a little gift from the Rails team allowing you to write code in your tasks that lives within your app’s pre-existing environment. The desc line serves as a comment about what the task does, and will appear alongside the task name when you query it with the —tasks parameter.

Within the body of the task we simply require the script we’re going to run, in this case my virtually unmodified utility class, and then we check to see if a parameter named NUM_USERS was passed in. If it was, we use that value to determine the number of users to create. If it wasn’t, we default to 5.

Because Rails is smart, and talented in the mystical arts, it auto-loads any files in lib/tasks that have a .rake extension. So just plop this file in that directory and you can then check the available Rake tasks from the top level of your project. You should see our new task definition there:

$ rake --tasks | grep sample
rake foo:sample_data              # Generate sample data for the app

Rockin. So let’s run it. As you can see from the output below, it calls the utility calss, creating 10 sample users (and a bunch of other stuff I’ve excluded). Couldn’t be easier.

rake foo:sample_data NUM_USERS=10
SampleData: generating 10 users, blah blah blah...

I hope this has been helpful, and if you’re looking for more information, make sure to check out Martin Fowler’s seemingly definitive reference.

blog comments powered by Disqus