Handy Ruby Gem: andand

I came across a really useful Ruby gem today: andand. In PHP web development, I usually use this idiom when retrieving an object from the database model:

$obj = $model->getObject($id);
if(null !== $obj) {
    doSomething($obj);
}

Obviously this is a little cumbersome, since I have to do this every single time I get an object using a function that might return null. Reginald Braithwaite, author of andand, has made this process a heck of a lot easier for all the Rubyists out there. His gem allows natural method chaining for functions that can return nil:

@phone = Location.find(:first, ...elided... ).andand.phone

This saves a lot of boilerplate code and improves readability. I like it.

Bookmark and Share

3 Responses

  1. With the last rails version you can do :

    @phone = Location.try(find(:first, …elided… )).try(phone)

    http://ryandaigle.com/articles/2008/11/20/what-s-new-in-edge-rails-object-try

  2. Sam Livingston-Gray

    Also check out Reg’s “Ick” gem (ick.rubyforge.org). The “maybe” method it contains works similarly to “andand” (but reads better, IMO), and there’s another version that takes a block — which is very useful if you find yourself writing something like:

    something.andand.spam.andand.eggs.andand.bacon

    Admittedly, sometimes the above can indicate a violation of the law of Demeter… but sometimes it really is what you want to do.

  3. [...] Chris Kite Posted in [...]

Leave a Reply