snax

safe nils in ruby

Groovy has a feature called safe navigation. It lets you send messages to nil and have them return nil if you’re in a special context. This is neat because it means in Grails views, where you might expect to do:

  ${ if (user.photo != NULL) {user.photo.url} }

You can instead do:

  ${ user.photo?.url }

The special context is explicitly signalled by the ? on the accessor.

ok switching to grails

Nah. What if we could add it to Ruby? Be aware that empty arrays behave this way already, because empty array comprehensions return [], which is safe to keep calling. So we just need:

class NilClass
  def method_missing(*args)
    super unless caller.first =~ /`_run_erb/
  end
end

Now, as long as we’re in a special context (ERb), we can chain our nils.

where should we keep it?

For now environment.rb makes a fine home. If it makes people feel better, I could put it in a plugin, or maybe a Rails patch. I am not using this in production (yet), but I want to hear thoughts.