Ruby Idioms from Open Source, Volume One - Seinfeld

This is the first in what I hope to be a series of articles looking at different open source projects and pulling out various ruby idioms.

We’re looking at Seinfeld which powers Calendar About Nothing. If you haven’t signed up yet, you should definitely do so. It is a fantastic way of keeping yourself motivated and contributing.

String Substitution

You can find the first bit of interesting code at line 371 of seinfeld_calendar.rb in the page_title method:

def page_title

  "%s's Calendar" % @user.login

end

Here we see String formatting substitution. You could also do sprintf(“%s’s Calendar”, @user.login), but why would you? Use an array if you have more than one value for substitution.

Date Manipulation

now        = Date.new(params[:year], params[:month])

prev_month = now << 1

next_month = now >> 1

Around line 58 of seinfeld_calendar.rb, we see that for the calendar’s next and previous month links to work properly, Seinfeld uses the << and >> methods which are described to

Return a new Date object that is n months earlier/later than the current one.

These methods were new to me, but they’re easy enough to remember if you think of them as looking like fast-forward and rewind.

Determining if a string is empty… wait, what?

Line 120 of /lib/seinfeld/models.rb gives us

  return if login_name.size.zero?

Which looks nice, but one can’t help but wonder why they didn’t use login_name.empty? instead. My benchmarks show .empty? to be trivially faster, but I may be missing something. Any ideas? My money is on it simply being the author’s preferred idiom. I think .size.zero? may be more readable, but I’ll stick with .empty? for the near future.

If you like learning by examining good examples of ruby code, I highly recommend David A. Black’s Ruby for Rails: Ruby Techniques for Rails Developers

If you have any suggestions for a future project to look at, please let me know.

1 Because projects are always changing these line numbers are just provided as-is at the time of writing.