Rake Task : Arguments for advanced usage
Rake tasks are really helpful. They come in for our help when need to perform some automated stuff and sprinkle the Ruby magic to create that big impact with least of the efforts.
I encountered a similar issue where a rake task was required to remove some records from specific tables and update status of some fields based on identification e.g. company_id, region_name. It was easy enough to write a rake task with certain specifics, target certain tables. Run it and forget it.
Now with Ruby’s commending DRY - Don’t repeat yourself mantra, I thought that maybe this rake task can be used for again for some other company or store in future. The train of thought started chugging.
What if ? :
- we could send in values as arguments to a rake task
- we could use those parameters to perform the magic in our task
Rake tasks allow us to do exactly that. Let’s see how we can do it:
Let’s see this in action:
On command line use the following command to execute our super rake task:
rake convert:defunct[2987, "Baner"]
Some terminal emulators can give trouble to execute this rake task so if your encounter an issue issue the command as
rake 'convert:defunct[2987, "Baner"]'
Now we will see how this actually works :
Two important parts of the whole code are highlighted and explained below:
Here we are asking rake to store the our parameters in an internal hash with keys as :company_id & :region_name and values are the ones that we input.
Here we access the values from the rake hash and assign them to variables which can be used further.
Now let your imagination fly and use this advanced rake method to achieve a greater magic!