Skip to content

Instantly share code, notes, and snippets.

@eladmeidar
Created July 21, 2009 03:21
Show Gist options
  • Save eladmeidar/151093 to your computer and use it in GitHub Desktop.
Save eladmeidar/151093 to your computer and use it in GitHub Desktop.
# File actionpack/lib/action_view/helpers/text_helper.rb, line 141
def excerpt(text, phrase, *args)
options = args.extract_options!
unless args.empty?
options[:radius] = args[0] || 100
options[:omission] = args[1] || "..."
end
options.reverse_merge!(:radius => 100, :omission => "...")
if text && phrase
phrase = Regexp.escape(phrase)
if found_pos = text.mb_chars =~ /(#{phrase})/i
start_pos = [ found_pos - options[:radius], 0 ].max
end_pos = [ [ found_pos + phrase.mb_chars.length + options[:radius] - 1, 0].max, text.mb_chars.length ].min
prefix = start_pos > 0 ? options[:omission] : ""
postfix = end_pos < text.mb_chars.length - 1 ? options[:omission] : ""
prefix + text.mb_chars[start_pos..end_pos].strip + postfix
else
nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment