Standalone script/runner bin scripts in Rails
script/runner
or script/rails runner
scripts are common in Rails apps for doing maintenance tasks. However, this
only works well until you have several arguments to parse from the command line. Putting standalone scripts in /bin
instead gives you easier, more flexible argument parsing and cleaner command lines and crontab entries.
Arguments with script/runner
First, you could just hack the argument parsing out, especially when using an argument delimiter like --
:
Not attractive, but here’s how:
Standalone bin script
All script/rails runner
does is parse the optional environment out of the command line, bootstrap the Rails code, and
then execute your code. If you assume RAILS_ENV
is set appropriately in your production crontabs, then it’s easy to do
this yourself.
The ideal command line:
Rails 3
Rails 2
Option Parsing
Using the standard boilerplate normally provided by script/rails runner
, this gives you a cleaner command line and
more flexibility with option parsing. When using optparse, optimist or other option
parsing libraries, you could still retain the -e <environment>
option. Otherwise, just set RAILS_ENV
appropriately
and you’re good to go.