Danie Roux

People person, change agent. Journeyer through problem and solution space. Interested in being interested.

Danie Roux header image 2

Dynamic tasks with Rake namespaces

December 29th, 2008 · 1 Comment · general

What we are trying to accomplish

We are using Rake to manage our database instances.

If a database is stopped, we want the task “database:start” to be available, but not “database:stop”. We have multiple databases running on the same server, the instance names should not be hard coded into the Rakefile.

These are the type of tasks we want to invoke:

rake development:stop
rake test:start
rake ci:status

Obviously we don’t want to define three, hard-coded namespaces (development, test, ci) and within each of those namespaces, three tasks (stop, start, status).

That would be tedious.

Simplest example

Luckily for us, Rake is still full-blown Ruby. This then is our first stab:

  • Iterate over a list of database names and define a namespace for each.
  • Within the defined namespace, define a task called “stop”, using the current scope (namespace) to get the database name.
["development", "test", "ci"].each do |databaseName|
  namespace databaseName do
    desc "stop"
    task "stop" do |t|
      puts "Action stop would now be performed on database #{t.scope}"
    end
  end
end

The task list of that file looks like this:

rake ci:stop # stop
rake development:stop # stop
rake test:stop # stop

Our own task type

We now want to define more tasks. Duplicating the task definition if only the action (stop, start, status, restart) change, seems like more tedious work. All we need to do is to define our own “task_database” that takes a database instance and an action to be performed on it:

The task list for this file looks like this:

rake ci:restart # restart - ci
rake ci:start # start - ci
rake ci:status # status - ci
rake development:restart # restart - development
rake development:status # status - development
rake development:stop # stop - development
rake test:restart # restart - test
rake test:start # start - test
rake test:status # status - test

I hope you find this useful. Similar code to this is now managing my GemStone instances :-)

Tags: ···

1 response so far ↓

Leave a Comment