Sandboxed Rake Tasks for Your Rails app!
Often times in your Rails app, you would run rake tasks to manipulate data in your database.
This could be for updating the attributes for a bunch of rows in table, or even for destroying records.
Let’s look at such an example of a rake task.
Here we are running this rake task to destroy records in a specific table.
Let’s run it:
Let’s make sure the records were actually deleted:
This rake task is simple, but what if we had a more complex use case?
And it dealt with manipulating tons of data?
And you had to run it on … the production database?
Risky, I know.
The Rails console actually provides a nifty way to deal with such cases.
The ‘sandbox’ mode.
Here’s the sandbox mode in action. It makes sure that any database action you do is rolled back when you exit the console.
That’s good, but this is applicable only for the Rails console.
Can we do the same for rake tasks?
Yes. We can!
Since rake or Rails does not give out of the box support for sandbox mode, we will write a container rake task which sets up the sandbox mode for us and will run the rake task of our choice.
If you are wondering where the code from opening and closing a transaction came from, it comes directly from the source code for rails console.
Now that we have the sandbox container rake task ready, let us run the same rake task again in sandbox mode.
Our container task takes in the name of the rake task we want to execute as an argument.
Here’s an example:
Now let us actually make sure that the records were not deleted:
And voila! It works:
So, to run your rake tasks in sandbox mode:
- Drop the
sandbox.rakefile in your Rails project.
bin/rake sandbox <name of your rake task>to run your task in sandbox mode.
How does this help?
- Write once, run everywhere.
sandbox.rakeis compatible with any rake task you’d write.
- Don’t keep writing code to start/stop database transactions in every rake task you’d write. Keep your rake tasks clean!
- Say goodbye to tensed rake task runs in production. Do a dry run of your task in sandbox mode, make sure everything is perfect before going for the real deal!