Thursday, July 12, 2012

blank?, present? or what?...

How do you test if a boolean field is false? I mean, if it has the value false, because nil has a boolean value of false in Ruby, right?

Let's see the Object API a bit


blank?()
An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank.

and


present?()
An object is present if it’s not blank?.


So probably you should be thinking that present? should be the method to use

myInstance.field.present? && myInstance.field?

But this is not correct, as myInstance.field.present? is false. myInstance.field.blank? is true, and so !true is false

So the solution is

!myInstance.field.nil? && myInstance.field?

Thing with this solution is we have a system of 3 values, because nil would be different than false.

Does this make sense?