Background Processing Using Rails Runner

Rails comes with a built-in tool for running tasks independent of the web cycle. The rails runner command simply loads the default Rails environment and then executes some specified Ruby code.

Some of use cases :

  1. Data import
  2. Execute methods of your models.
  3. Sending batch emails
  4. Nightly report generation

Showing here some code example for

Let’s say you want to generate a nightly report and send it out to multiple users

1
rails runner DailyReport.send_me!

This will execute send_me! method for DailyReport class.

rails runner will give us access to all rails environment so we can even use the Active Record finder methods to extract data from our application.

1
rails runner 'User.all.map(&:email).each {|e| puts e }'

Here we are just listing out emails of all users in our system.

1
rails runner -h

Output will be

1
2
3
4
5
6
7
8
9
10
11
12
13
Usage: runner [options] ('Some.ruby(code)' or a filename)

    -e, --environment=name           Specifies the environment for the runner to operate under (test/development/production).
                                     Default: development

    -h, --help                       Show this help message.

You can also use runner as a shebang line for your scripts like this:
-------------------------------------------------------------
#!/usr/bin/env /Users/raysrashmi/checkouts/foobar/script/rails runner

Product.find(:all).each { |p| p.price *= 2 ; p.save! }
-------------------------------------------------------------

A sample crontab to run that script might look like

1
  @daily  /Users/raysrashmi/checkouts/foobar/script/rails runner -e production 'DailyReport.send_me!'

This script will run daily to send out daily report. The Rails Runner is useful for short tasks that need to run infrequently. But jobs that require more heavy work are best handled by other libraries. I use rails runner whenever I need to run a small task.

Reference links :

There are other better library available for handling background process. But here I wanted to talk about rails runner