Runt on Ruby on Rails

August 14th, 2006, By Duncan Gough

Date calculation is a pain in the arse. Runt is the fix. To quote the Runt homepage, “Runt is an implementation of select temporal patterns by Martin Fowler in the super-fantastic Ruby language”.

However, not a lot of people seem to have put Runt together with Ruby on Rails, so here’s my guide for doing just that. Disclaimer:, for the purpose of this how-to, it’s better than you think of me as the worst programmer in the world, since I’m not a Ruby native, it’s all about the end results for me at the moment. If you spot any errors, please get in touch and I’ll update this post accordingly.

HOWTO: Runt on Ruby on Rails (on Textdrive)

#1. This HOWTO assumes that you’re developing the site on your local machine/laptop and using svn to commit those changes to the live site. Part of the problem I had getting Runt to work on textdrive was down to the fact that I wasn’t able to install Runt without root priviledges. The ever-helpful Textdrive support told me about using a rake task to freeze gems and other plugins into the Rails lib/ directory, which was the ideal solution.

#2. Install runt from source on your local machine

#3. Run rake freeze_other_gems to freeze runt in your apps’ lib/ directory.

#4. Add the following to your config/environment.rb

require 'runt'
require 'date'

include Runt
include DPrecision

#5. svn commit and svn update your production site

#6. Create the following ruby code as runt_test.rb in your lib/ directory, (taken from the Runt tutorial)

require 'runt'
require 'date'

include Runt
include DPrecision

last_thursday = DIMonth.new(Last_of,Thursday)

august = REYear.new(8)

expr = last_thursday & august

expr.include?(Date.new(2002,8,29)) #Thurs 8/29/02 => true
expr.include?(Date.new(2003,8,28)) #Thurs 8/28/03 => true
expr.include?(Date.new(2004,8,26)) #Thurs 8/26/04 => true
expr.include?(Date.new(2004,3,18)) #Thurs 3/18/04 => true

expr.include?(Date.new(2004,8,27)) #Fri 8/27/04 => false

#7. Execute ruby lib/runt_test.rb and you should see the following output:

true
true
true
false
false

#8. Notice that the fourth expr test evaluates to false, not true as the comment suggests. The code is correct and the comment is wrong though, so don’t worry too much.

#9. Restart your webapp and check for any errors throughout the site as a result of Runt being loaded in the environment.rb. For example, I had the line ‘Test::Unit.run = true’ in my environment.rb to remove a debugging line that appeared to be as a result of a bug in the file_column plugin. Commenting this line out solved a minor conflict with Runt and everything else went fine.

#10. That’s it. Runt is now available to your Rails app.

« PreviousNext »