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}
end
all_stories << story
end

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

3 comments:

Chris Kilmer said...

Hey Daniel,
I just posted an article about passings args to rake tasks a little earlier this morning. Perhaps it could provide a few hints...

http://www.betweentherails.com/2008/01/rake-args-new-hottness.htm

Daniel Neighman said...

Hey Chris,

That's cool. Thanx for the link :)

ivey said...

You can also use the "rule missing" trick I picked up from Geoffrey Grosenbach:

rule "" do |t|
# do anything you like based on t.name
end

There's an example in Merb's Rakefile for running specific specs.