Run Local Scripts on Heroku

In order to run an arbitrary script on Heroku, you can use the Heroku console. They state that “you can use heroku console as a stand-in for Rails’s script runner”, but one key component of the script runner is that you can run files. You can run files in your git repository that are deployed to the instance that you want to run them on by using the method advocated by Steve Wilhelm.

What if the file is not checked in or you need to make rapid modifications for prototyping? If you have a lot of code that you want to write and you want to be able to easily modify it, try the solution below. Manually typing in many multi-line statements at the console (and retyping when you make an inevitable mistake) is frustrating.

First, create a file called something like semicolonify.rb, and make it executable:

#!/usr/bin/env ruby
puts[0]).split("\n").delete_if{|line| line =~ /^\s*#/}.compact.join(';')

Then you can run semicolonify.rb on your ruby file, and pipe the output to a temporary file:

$ ./semicolonify.rb your_actual_ruby_file.rb > temp.rb

After that, you can run something like:

$ heroku console --app APPNAME `cat temp.rb`

This will run the commands you specify through the heroku console, one line at a time. You can add your own functions, etc. Based on my understanding, you need to run semicolonify.rb because the console gets confused when it sees blocks that are not terminated. The only limitation (based on my implementation) is that trailing comments cause things to get mucked up. Also, make sure you don’t have a long-running (> 30 second?) script, or Heroku will cut you off. There are probably additional things that I need to add to the semicolonify.rb script, but this seems to work for now.

Categories: development

« How to Run A Successful Brown Bag System Fixing Sporadically Failing Specs »