activesupport

Object#presence

Have you ever written such code:

title = (obj.title.blank?) ? "Untitled" : obj.title

Turns out, there’s a much shorter way to do this. Object#presence from ActiveSupport is a method that returns nil if the object is blank, and the object itself if it’s not. The result is that you can chain several alternatives and the first one that is not blank will be used:

title = obj.title.presence || obj.name.presence || "Untitled"

BTW, in case you didn’t know, Object#present? is the opposite of blank?, and is often more convenient. “object (is) present” just sounds better than “not object (is) blank”…