I found out today how to have small stand-alone ruby scripts that run in a specific Rails environment.

We’ve recently been decommissioning one of our 18-year-old apps by porting its functionality from an old J2EE service to less-old Rails app. The 11-year-old Rails app is used for administering a database of all sorts of entities, and is still heavily used by parts of the business. An export of a subset of this data was pulled from the J2EE server by Jenkins and put into another server where it is used at runtime (essentially a publishing workflow).

We’re retaining that publishing workflow at the moment, so we wanted Jenkins to be able to run the new export script on the Rails server (in the night when no one is using it).

The export script needs to run within the rails environment of the app; this is so that it can access all the ActiveRecord entities. We’re using rvm to handle the ruby versions, so the way we do this is like so:

source ~/.rvm/scripts/rvm
rvm use ruby-2.1.2
cd $BASE || exit 1
RAILS_ENV=stage rails runner lib/export.rb

A script like this is checked in with the project and so ends up on the final server. We can then use Jenkins to ssh into the machine to run the script to produce the export. Although not shown here, the script also copies the export out to storage service where further jobs run to publish it to the runtime environment.