Rake tasks

Overview

We use Rake to perform batch operations on the database.

Creating and running a Rake task

  1. Create a new file in lib/tasks with a descriptive name and the .rake extension
  2. Ensure you set the namespace to a relevant context
  3. Add a suitable description
  4. Add the task name (usually best if this matches the file name)
  5. Add the desired operations attached to the required model classes
  6. Example rake files:
Task with no arguments
namespace :<CONTEXT> do
  desc "<DESCRIPTION>"
  task <TASK_NAME>: [:environment] do
    <VAR_NAME> = <MODEL_CLASS>.new(<...>)
    <VAR_NAME>.save!
  end
end

In your terminal run docker-compose run --rm web bundle exec rake <CONTEXT>:<TASK_NAME> RAILS_ENV=<ENVIRONMENT>

  • CONTEXT: as defined for your namespace
  • TASK_NAME: As defined for the task
  • ENVIRONMENT: development, staging or production
Task with arguments
namespace :<CONTEXT> do
	desc "<DESCRIPTION>"
	task :<TASK_NAME>, [:<ARG_1>, :<ARG_2>] => [:environment] do |t, args|

		<VAR_NAME> = <MODEL_CLASS>.new(<ARG_1>: args.<ARG_1>, <ARG_2>: args.<ARG_2>)
		<VAR_NAME>.save!
	end
end

In your terminal run docker-compose run --rm web bundle exec rake "<CONTEXT>:<TASK_NAME>[ARG_1,ARG_2]" RAILS_ENV=<ENVIRONMENT>

  • CONTEXT: as defined for your namespace
  • TASK_NAME: As defined for the task
  • ENVIRONMENT: development, staging or production
  1. Confirm that the desired changes have been made to the DB

NOTE: Remember to test your tasks thoroughly before running them on the production Heroku container as these will have a permanent effect on the database.