matthew ephraim

Dynamic Rake Tasks

This is a quick little Ruby trick that I thought was pretty neat. If you have a Rake file and you have a bunch of similar tasks that you don’t want to have to write by hand, you can dynamically generate the Rake tasks by using a little bit of Ruby code.

For example, maybe I want to change the contents of a few different directories on my file system. And say that I want to have a different rake task for each directory, so that I can type something like this:

Command line
rake modify:songs

Or like this:

Command line
rake modify:documents

With a small number of directories, it wouldn’t be a big deal to write a task for each directory. But, if I have 100 directories, that might get to be a little bit tedious. So, instead of writing the tasks manually, I’ll have Ruby do it:

rakefile.rb
namespace :modify do
	[:music, :documents, :application, :home].each do |directory|
		task directory do
			change_contents(directory)
		end
	end
end

In the code above I’m taking an array of 4 directories and using that array to call the Rake task function to create a new task for each directory. I’m also passing the name of the directory on to a function that changes the contents of the specific directory.

It’s a pretty simple trick, but it’s definitely come in handy for me.