Safe Nils and Try

March 1st, 2008 1 Comment »

Chris over at ozzm.org just posted an awesome little snippet of code.

class Object
  ##
  #   @person ? @person.name : nil
  # vs
  #   @person.try(:name)
  def try(method)
    send method if respond_to? method
  end
end

I took it a step further and allowed args and blocks to be passed to it.

Object.class_eval do
  def try(method, *args, &block)
    send method, *args, &block if respond_to? method
  end
end

Now not only can you do things like @person.car.try(:running?) but you can do things like Kernel.try(:puts, "Oh Wow This Is AWESOME!")

The block portion lets you do things like:

def blah
  yield
end

try(:blah) do
  puts "wow, blah works and it yielded to this block!"
end

All in all it’s pretty sweet, but it definitely lets you abuse demeter. And by abuse it I mean the taking out back and beating with a rubber hose kind of abuse. For example @car.try(:person).try(:parent).try(:siblings).try(:first).try(:is_male?).

So, don’t be evil, use it well.