Jonathan Martin
Articles tagged “extension”
-
Ruby Extension: HTML Truncation
~ by Jonathan Martin
Another tip (err hurdle) I came across during the production of this blog — truncating an HTML string. Easy, right?
It seems simple enough: shorten some basic text content from a long entry. It’s extremely popular in blogs, catalogs, portfolios, etc. and with good reason — the average browser wants to find content through screening, not mass scrolling.
But a good trimmer must keep a few things in mind.
- Don’t split words
- Recognize/respect HTML tags
- Parse HTML according to standards
These add up to some pretty terse requirements once you actually get to coding. First, unless we want to manually parse HTML, we’ll have to use some standards based parser and loop through all the elements, until the specified number of characters/words (excluding tags!) is exceeded, at which point we append a user-defined tail and discard all other tags.
Update: the latest version of this handy widget is now available as a gem! Check it out at rubygems.org/gems/butter or bundle it with gem install butter.