Batch Processing with Rails
April 18th, 2006
I just recently ran across another nice thing you can do with Ruby on Rails that I thought others may find useful. I have developed a few different Rails apps and in several cases, I have found that I really needed a way to perform some process in the background outside of the web server. This could serve a variety of purposes, such as for slicing and dicing your data into reports or performing some resource intensive tasks.
Ruby On Rails provides a simple way to take advantage of your existing Rails code from the command line. For this example, let’s say we want to create a script called do_something_magical. So, we can just create a file in the scripts directory of our Rails app and call it do_something_magical.rb. Then, at the top of this script, just add this one line to make your script run within the Ruby On Rails environment:
require File.join(File.dirname(__FILE__), '../config/environment')
Now this script will be able to access all of your other Rails code. For instance, to include your secret_ingredients model, you can just require it like so:
require 'secret_ingredients'
Likewise, if you have a magic_maker dependency in your lib directory you can include it as follows:
require_dependency 'magic_maker'
I found this to be a great time saver when I need to do some heavy lifting with my existing Ruby On Rails code.
Subscribe to the feed!
November 6th, 2007 at 10:05 pm
Hey Tom,
This is a long time since you posted this, but it’s going to be very helpful!
I have an additional question : how to start this batch process when I start my server?
November 6th, 2007 at 10:13 pm
Hi Julien,
It has been a while but I still use this sort of thing all the time :)
One other option is to just use the built-in script/runner that comes with rails if you are just doing a once off thing. For instance, I typically just create a helper on my Model and then do:
script/runner “MyModel.dosomething()”
To run this when your server starts I recommend just using “cron”, or on Windows you can use “at”. If you are on linux there is also an @reboot option that will run it every time the server starts… you will have to Google for details. Good luck.