Ruby/Rails: Overriding NilClass

Rails uses “whiny nil”, which means if you call a method on an object that happens to be nil (null), you get an exception. This is good. But with strings in a web app (in any language), you often don’t know if an empty string will be nil or simply zero-length (“”). That’s because some code will see a form submitted with a whitespace string and make it nil, while others will make it “”. These might be my libraries or the web framework’s libraries or plugin libraries. This leads to ugly code like this:

  1. @message = "Oi! Enter your name fella" if name or name.empty?

When we really just want

  1. @message = "Oi! Enter your name fella" if name.empty?

So I derive great pleasure from overriding NilClass like so:

  1. class NiClass
  2.   def empty?
  3.     true
  4.   end
  5. end

3 thoughts on Ruby/Rails: Overriding NilClass

Leave a Reply