Chris Kite Programming, Computer Security, Etc.

Handy Ruby Gem: andand

04.08.2009 · Posted in Ruby

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) {

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... )

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


3 Responses to “Handy Ruby Gem: andand”

  1. With the last rails version you can do :

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

  2. Sam Livingston-Gray says:

    Also check out Reg’s “Ick” gem ( 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:


    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

SEO Powered by Platinum SEO from Techblissonline