Jeff Dean's blog



Jeff DeanJeff Dean
ActiveModelListener and AutoTagger become better Ruby citizens
edit Posted by Jeff Dean on Friday May 14, 2010 at 10:05PM

If you use auto_tagger in conjunction with a continuous integration build you may have noticed that the autotag executable exits with a status code of "1" when it shouldn't. Thanks to Sarah Mei I just pushed version 0.1.5, which fixes this bug. Thanks Sarah!

If you use active_model_listener, you are probably pretty tired of that active record deprecation notices. After Todd Persen pointed this out to me I just pushed version 0.2.5 which fixes this.

Jeff DeanJeff Dean
Pivotal Labs Happy Hour - Friday before GoRuCo
edit Posted by Jeff Dean on Friday May 14, 2010 at 08:30AM

Pivotal Labs is hosting a happy hour the Friday before GoRuCo at the Blue Owl.

We're looking for brilliant Rails developers to join our team. If you're looking for somewhere to do serious agile development, and serious Rails development, this is the place to go.

196 2nd Ave, New York, NY 10003

5/21/2010, 7:00 pm - 9:00 pm

Jeff DeanJeff Dean
Hash#fetch for fun and profit
edit Posted by Jeff Dean on Saturday May 08, 2010 at 10:18PM

I have an app where I set the alt tag of images with javascript. To reduce the size of the page, I want to emit img tags with no alt attribute, however that is not currently possible:

image_tag "foo.png", :alt => nil # => <img alt="Foo" src="/images/foo.png" />

I agree that images should have alt tags, and I agree that the Rails default is sensible. However, if I explicitly send :alt => nil, I expect it to omit the alt attribute altogether, to be consistent with :class and other html attributes.

This happens because under the hood the code looks like this:

options[:alt]     ||= File.basename(src, '.*').capitalize

See the issue? If options[:alt] is falsey, the default is used. Since nil is falsey, there's no way to get options[:alt] to be nil. My requirement is:

  • If I pass an :alt attribute (even if it's nil), use the passed in value
  • If I pass no :alt attribute, use the default

Making this happen is very simple with the marvelous Hash#fetch:

UPDATE: Thanks to Brennan Falkner and Mark-Andre Lafortune for pointing out the block syntax of fetch is the preferred way.

options[:alt] = options.fetch(:alt) { File.basename(src, '.*').capitalize }

Instead of evaluating the truthiness of the :alt value, fetch checks for the existance of the :alt key. For those of you who are interested in getting this into rails core, apply the patch and give a +1 to the related Lighthouse Ticket.