Use Ruby to Truncate a String to Display Context Around a Search Term (plus term highlighting)

The following code will allow you to pull a search term and its context out of a larger string. It can be modified to use offsets as the start/finish points for the term rather than looking for the term itself. I'll end up doing this myself as the actual application this will be used in is semantic-based and the term a user searches for could have synonyms or relationships to other words which will also produce results. In this case it would be dangerous to highlight the original search term.