Sunday, November 30, 2008

Use .blank? instead of .nil? && .empty?

So I had an issue tonight where the app was working fine, but a bunch of my tests were blowing up. Turns out that when you have a blank string field in a form, instead of putting a NULL value in the db, it puts in an empty string. Kind of annoying, but there you go. Unfortunately, in my tests I wasn't passing a param for fields I wasn't explicitly setting, so there it did put NULL in the db.

In my view code, I was calling .empty? on the property, which worked fine in the app (where the db provided a blank string), but choking in the tests, where it became nil.empty?. I thought, 'Well, I could check for both...' but that just rubbed me the wrong way. 'Surely, Ruby and/or Rails has a more elegant solution?' And indeed, Rails does: the blank? method. From Programming Ruby: The Pragmatic Programmers' Guide, Second Edition:

To make it easier to tell whether something has no content, Rails extends all
Ruby objects with the blank? method. It always returns true for nil and false, and
it always returns false for numbers and for true. For all other objects, it returns
true if that object is empty. (A string containing just spaces is considered to be
empty.)
puts [ ].blank? #=> true
puts { 1 => 2}.blank? #=> false
puts " cat ".blank? #=> false
puts "".blank? #=> true
puts " ".blank? #=> true
puts nil.blank? #=> true

Eeeeexcellent.

0 comments: