Hash Defaults and Nested OrderedHash in Rails

Posted by Peter Wagenet Thu, 01 Oct 2009 01:43:00 GMT

Thanks to ruby_switcher.sh I now have Ruby 1.9 running on my machine. Subsequently, I’ve just run into my first Ruby 1.9 induced bug: I relied upon 1.9’s Hash ordering. Fortunately, Rails’ ActiveSupport has it’s own undocumented OrderedHash implementation for Ruby 1.8. Unfortunately you can’t create an OrderdHash using the hash literal notation (i.e { :a => 1, :b => 2 }) so making a nested OrderedHash could be painful.

ActiveRecord #find_by_id with Conditions and NotFound Exception

Posted by Peter Wagenet Sat, 05 Sep 2009 20:07:00 GMT

Every so often I’ve seen code (maybe even written by yours truly) that looked something like this:

post = Post.first(:conditions => { :id => 1, :published => true })

However, this won’t raise an error like a #find(id) would. So then the following line is added:

post = Post.first(:conditions => { :id => 1, :published => true })
raise ActiveRecord::RecordNotFound unless post

But this is getting a bit messy and seems overly complicated. Fortunately, we have a better solution.

Ironically, this solution is actually well documented in the Rails docs. Any call to ActiveRecord::Base#find accepts an options hash. This means we can do things like:

post = Post.first(1, :conditions => { :published => true })

Now that looks much better.

Coloration in Autotest with TestUnit 2.0.3 1

Posted by Peter Wagenet Fri, 04 Sep 2009 20:41:00 GMT

I recently discovered that even though TestUnit 2.0.3 has support for for coloration, coloration does not show in Autotest. Previously, the redgreen gem had taken care of this, but now that TestUnit itself supports coloration the redgreen gem is no longer necessary (not to mention the fact that it’s broken with Ruby 1.9 and TestUnit 2.0.3). TestUnit supports a –use-color flag, but because of the unique way in which Autotest loads the tests I was unable to figure out how I could pass this flag. Furthermore, –use-color defaults to false when the command is passed to a pipe, which Autotest also does.