diff options
author | root <mohamed.o.alnagdy@gmail.com> | 2014-07-16 19:48:07 +0200 |
---|---|---|
committer | root <mohamed.o.alnagdy@gmail.com> | 2014-07-16 19:48:07 +0200 |
commit | a9d3b77e494608cedcdad86d7e0c8a07694ffea5 (patch) | |
tree | f6800b11d589dd9752721b62fefa87b1d1d6aaee /activesupport/lib/active_support | |
parent | 002cf5fac4d71e77805c0e1dad3b9499b1f551ca (diff) | |
download | rails-a9d3b77e494608cedcdad86d7e0c8a07694ffea5.tar.gz rails-a9d3b77e494608cedcdad86d7e0c8a07694ffea5.tar.bz2 rails-a9d3b77e494608cedcdad86d7e0c8a07694ffea5.zip |
Added truncate_words method to activesupport strings
Diffstat (limited to 'activesupport/lib/active_support')
-rw-r--r-- | activesupport/lib/active_support/core_ext/string/filters.rb | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/string/filters.rb b/activesupport/lib/active_support/core_ext/string/filters.rb index 49c0df6026..2029909486 100644 --- a/activesupport/lib/active_support/core_ext/string/filters.rb +++ b/activesupport/lib/active_support/core_ext/string/filters.rb @@ -62,4 +62,25 @@ class String "#{self[0, stop]}#{omission}" end + + # Truncates a given +text+ after a given number of words<tt>words_count</tt>: + # + # 'Once upon a time in a world far far away'.truncate_words(4) + # # => "Once upon a time..." + # + # Pass a string or regexp <tt>:separator</tt> to specify a different separator of words: + # + # 'Once<br>upon<br>a<br>time<br>in<br>a<br>world'.truncate_words(5, separator: '<br>') + # # => "Once<br>upon<br>a<br>time<br>in..." + # + # The last characters will be replaced with the <tt>:omission</tt> string (defaults to "..."): + # + # 'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)') + # # => "And they found that many... (continued)" + def truncate_words(words_count, options = {}) + sep = options[:separator] || /\s+/ + sep = Regexp.escape(sep.to_s) unless Regexp === sep + return dup unless self =~ /^((?:.+?#{sep}){#{words_count - 1}}.+?)#{sep}.*/ + $1 + (options[:omission] || '...') + end end |