Created
August 18, 2009 14:45
-
-
Save delameko/169750 to your computer and use it in GitHub Desktop.
Smart Truncate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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