Widon't you just use Ruby?
September 22, 2006
I recently came across a post by Shaun Inman describing a term I had not heard before (at least with regard to typography): Widowing. Widowing is when a word flows to the next line only to end up all by its' lonesome. See Shaun's post on the matter for a spiffy visual aid and a PHP function (in the form of a Wordpress plugin) to give those widows some company.
We needed a function like this in a Rails project currently underway, so I cooked up a Ruby solution using Shaun's PHP as a guide. I chose to extend the String class, placing the file in the lib directory of my rails project and including it via the application controller.
# lib/string_utils.rb
class String
def widont()
space = self.rstrip.rindex(' ')
return self if space.nil?
self[0, space] + ' ' + self[space + 1, self.size]
end
end
Now we can use it on any HTML bound string when we need to prevent widowing.
>> a = "This is sort of a long string that might leave a widow."
>> a.widont()
=> "This is sort of a long string that might leave a widow."
I'm sure some Ruby whiz could pare that down to a single line, but it does the trick.
Disclaimer: I am well aware that this very post may contain widows, and can appreciate the irony.