Skip to content

Instantly share code, notes, and snippets.

@vilterp
Created March 7, 2009 22:05
Show Gist options
  • Save vilterp/75465 to your computer and use it in GitHub Desktop.
Save vilterp/75465 to your computer and use it in GitHub Desktop.
# loosely based on Rails' excerpt helper
# http://rails.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M001713
# TODO: don't break in the middle of words
def excerpts(text, word, options={})
omission = options[:omission] || '...'
radius = options[:radius] || 5
word.class == String ? re = /(#{Regexp.escape(word)})/ : re = word
return nil unless text =~ re
ans = ""; start = 0; last_range = -2..-1
while text[start..-1] =~ re
match_index = start + (text[start..-1] =~ re)
start_ind = [0, match_index - radius].max
end_ind = [match_index + text[start..-1].match(re)[0].length + radius, text.length - 1].min
unless last_range.include? start_ind-1
ans.rstrip!; ans << omission unless start_ind == 0
last_range = start_ind..end_ind
ans << text[last_range].lstrip
else
ans << text[last_range.end+1..end_ind]
last_range = last_range.begin..end_ind
end
start = match_index + text[start..-1].match(re)[0].length
end
ans.rstrip!; ans << omission unless last_range.end == text.length-1
options[:highlight].nil? ? ans : ans.gsub(re,options[:highlight])
end
puts excerpts('a string which contains many instances of the word string. the end','string',:highlight => "[\\1]")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment