Skip to content

Instantly share code, notes, and snippets.

@palexander
Created October 30, 2009 17:08
Show Gist options
  • Save palexander/222534 to your computer and use it in GitHub Desktop.
Save palexander/222534 to your computer and use it in GitHub Desktop.
##
# Get the context for a search term and highlight the term itself
# text: string containing the search term and additional information
# term: string with the term you're looking for
# words: int for how many words to include total
# padding_left: int for characters to the left of the search term
# padding_right: int for characters to the right of the search term
#
# Only handles the first instance of a given term. Can be modified to take
# character positions denoting the start and stop of term(s).
##
def search_term_context(text, term, words, padding_left, padding_right)
# Find out where our term appears in the string.
term_index = text.downcase.index(term.downcase)
term_index_after_strong = term_index + 8
# Check to see if the padding is greater than the beginning of the string.
str_start = term_index < padding_left ? 0 : term_index - padding_left
# If our end point with padding is longer than the text, use text length as end
end_test = term_index + term.length + char_after
str_end = end_test > text.length ? text.length : end_test
# str_start and str_end will buffer the search term
# If your text might contain partial words at the beginning, change the 0
# below to a 1, which will chop off the first (possibly partial) word from
# the array.
text = "... " + text.slice(str_start,str_end).split[0..(words-1)].join(" ") + " ..."
# Make the annotated term bold.
text = text.insert(term_index, "<strong>")
text = text.insert(term_index_after_strong + term.length, "</strong>")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment