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:
Post a Comment