Sandboxed Rake Tasks for Your Rails app!

Safe and Sound! Photo by rawpixel on Unsplash

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:

  1. Drop the sandbox.rake file in your Rails project.
  2. Execute bin/rake sandbox <name of your rake task> to run your task in sandbox mode.
  3. Profit!

How does this help?

  1. Write once, run everywhere. sandbox.rake is compatible with any rake task you’d write.
  2. Don’t keep writing code to start/stop database transactions in every rake task you’d write. Keep your rake tasks clean!
  3. 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!

Thanks for reading! If you have any suggestions or anything else you want to share with us, feel free to reach out by writing a response below.

PS: At Reflektive, we are building a team of empathetic and passionate people. If this resonates with you, join us on our journey.