Friday, January 11, 2008

Dynaically Setup Rake Tasks

This is probably really old news. I just setup my first rake task tonight though so I thought I'd put it up here. This is more for myself really so if it's not your cup of tea turn away now.

I've been playing with rSpec's text stories in Merb but I couldn't find a way to make a rake task that would take an argument for a particular story to run. e.g.
rake story:run my_story
So I've done the next best thing. I scan my directory for story files and create the rake tasks dynamically. Now I can use:
rake story:run:my_story
As well as
rake story:run:all
The code to make this dream a reality is
# Allows all found stories to be run individually by using
# rake story:run:story_name
namespace :story do
namespace :run do
all_stories = []
Dir.glob('stories/stories/**/*.rb').each do |path|
story = path.split("/").last[0..-4]
desc "Run spec story #{story}"
task "#{story}".to_sym do
sh %{ruby stories/stories/#{story}.rb}
all_stories << story

desc 'Run all stories'
task :all do
all_stories.each do |story|
sh %{ruby stories/stories/#{story}.rb}