Skip to content

Instantly share code, notes, and snippets.

@delameko
Created August 18, 2009 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save delameko/169750 to your computer and use it in GitHub Desktop.
Save delameko/169750 to your computer and use it in GitHub Desktop.
Smart Truncate
module ApplicationHelper
def smart_truncate(s, opts = {})
opts = {:words => 12}.merge(opts)
if opts[:sentences]
return s.split(/\./)[0, opts[:sentences]].map{|s| s.strip}.join('. ') + '.'
end
a = s.split(/\s/) # or /[ ]+/ to only split on spaces
n = opts[:words]
a[0...n].join(' ') + (a.size > n ? '...' : '')
end
end
smart_truncate("a b c. d e f. g h i.", :sentences => 2) #=> "a b c. d e f."
smart_truncate("apple blueberry cherry plum", :words => 3) #=> "apple blueberry cherry..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment