Monthly Archives: May 2009

Testing for existence with “blank?”

I know, I know, all ruby posts should be about slightly new takes on testing paradigms or other amazing best practices, but sometimes I think we skip the basiscs. Today it’s blank?.

ActiveSupport, the Rails extensions to ruby’s standard library introduce the method blank?. It’s pretty handy, and I think people tend to take it for granted without realizing exactly what its semantics are. blank? is handy if you want to treat an empty string, array, or hash as false.

Here’s a slightly haphazard table showing nil?, empty?, and blank? all work.

Input nil? empty? blank?
” “ FALSE FALSE TRUE
nil TRUE ERROR TRUE
1 FALSE ERROR FALSE
0 FALSE ERROR FALSE
“hi” FALSE FALSE FALSE
[] FALSE TRUE TRUE
[ [] ] FALSE FALSE FALSE
[ nil ] FALSE FALSE FALSE
[ 1 ] FALSE FALSE FALSE
true FALSE ERROR FALSE
false FALSE ERROR TRUE
{} FALSE TRUE TRUE
{1=>2} FALSE FALSE FALSE

So if you want a flexible way of testing whether something exists, blank? will often give you what you want. I’m sure that was just thrilling!

Advertisements

1 Comment

Filed under Uncategorized

OpenGem is on RubyForge

Hey quick note, OpenGem is now on RubyForge, so you can all just do:

gem install open_gem

Hoorah!

Leave a comment

Filed under Uncategorized

Creating Sample Data

Nothing earth shattering today, but I thought it was neat.  Every now and then I come across a document I would like to add to my test suites for a project, but there’s a problem.  The document might contain email addresses, phone numbers, who knows what, and I don’t really want that to be sitting around in my codebase, but the structure of the document matters.  The solution? Pipe it through this:

tr 'A-Za-z0-9' 'a-ff-aa-fa-ff-aa-fa-ff-aa-f001122334455'

Now all of your punctuation and such is preserved for your parsing pleasure, but the data is somewhat obfuscated. Of course use it at your discretion.

For bonus points, I actually made it into a TextMate command. Now I can have my test data, and feel reasonably safe about it.

Leave a comment

Filed under Uncategorized