Create Rake Tasks


Initial Setup

Creating rake tasks is an easy way to automate processes in rails. A sample rake task is found below. This specific tasks accepts two arguments, which are denoted using symbols in array format.

# lib/tasks/users.rake
require 'rake'

namespace :users do
  desc "Accepts a preset quantity of users to create along with an assigned role '[30, editor]'"
  task :add_users_with_role, [:qty, :role] => [:environment] do |t, args|
    args[:qty].to_i.times do |n|
      # your code here
    end
  end
end

To run this is in the command line is as follow rake users:add_users_with_role'[30, editor]'. It needs to have single quotes around it to accept the arguments. The arguments will be passed in as strings and will need to be modified as desired.

Invoking Other Rake Tasks

This will allow you to use other rake tasks within another certain rake task if needed.

task :invoke_one do
  Rake.application.invoke_task("users:add_users_with_role[30, visitor]")
end

# or if you prefer a more traditional syntax...
task :invoke_one do
  Rake::Task['users:add_users_with_role'].invoke(30, 'employee')
end

List Tasks

To get a current list of all available rake tasks, use the following command.

rake -T

Cron Jobs

To set up your rake task as a cron job, change the timing of the snippet below and app to match your desired options.

00 00 * * * cd /path/to/app && /usr/local/bin/rake RAILS_ENV=production task:my_task

Here's a cron job time generator.