Passing Parameters To Rake Tasks

Posted on March 14th, 2008

  I raised a question in our last meeting about passing parameters into rake tasks. I was surprised that there wasn't an immediate answer to the problem and only a few references to it online.

   After messing around with some of my own tasks and taking some of the thoughts brought up in the meeting it turns out that this is quite simple and it appears it is also under utilized as there is quite a bit of experience in our group and it doesn't appear than anyone has tried it.


Simple example

  To pass parameters into rake tasks you simple append a key = value hash to the end of your rake command. So if you had a task foo in namespace bar and you wanted to pass in a variable called 'snafu' you call the following.



$>rake foo:bar snafu='situation normal all frakked up'

  The one caveat here is that obviously you have to have some knowledge of the parameter names used in the task. So your rake file would look something like this. Notice that your variables are accessed via the ENV hash.



namespace :foo do

  desc 'testing parameter passing'
  task :bar do

    puts "you passed in the parameter snafu = #{ENV['snafu']}"

  end

end

  So why would I want to do this in the first place? In my case I wrote a task to do some data related operations on 80K records and I wanted to be able to specify the number of or type of records on which to perform the task without having to write a different script for each instance or change the script itself for each run of the task.


Thoughts on multiple parameters

   It can get cumbersome if you have a task that needs several parameters. My current solution is to use to use a single params hash member and then parse out multiple values from it in the task. This has the added bonus of not requiring the person running the task to have to know anything about the names you've used inside your task they only need to be aware of the params hash.



$> rake foo:bar params=var1,var2,var3,var4

Note that you will need quotes around your params list if it contains any unescaped white space.


1 Response to “Passing Parameters To Rake Tasks”

  1. Brent Dillingham Says:

    Whoo! I actually used this the other day ;) Thanks!

Sorry, comments are closed for this article.