diff options
author | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2014-07-16 16:44:02 -0300 |
---|---|---|
committer | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2014-07-16 16:44:02 -0300 |
commit | 5284bbbe1e4c46d226202b71015d3ab8539751f3 (patch) | |
tree | 057d963ca9dc593209636115418f5b64a953969d /activesupport/lib/active_support/core_ext/string/filters.rb | |
parent | 9bbb3ca3066fc5dbaeddad97d995dbe435d0a031 (diff) | |
parent | 41679b2b31f88de2bf176197d883bc95dcb0a2f2 (diff) | |
download | rails-5284bbbe1e4c46d226202b71015d3ab8539751f3.tar.gz rails-5284bbbe1e4c46d226202b71015d3ab8539751f3.tar.bz2 rails-5284bbbe1e4c46d226202b71015d3ab8539751f3.zip |
Merge remote-tracking branch 'origin/master'
Diffstat (limited to 'activesupport/lib/active_support/core_ext/string/filters.rb')
-rw-r--r-- | activesupport/lib/active_support/core_ext/string/filters.rb | 24 |
1 files changed, 24 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..1dfaf76673 100644 --- a/activesupport/lib/active_support/core_ext/string/filters.rb +++ b/activesupport/lib/active_support/core_ext/string/filters.rb @@ -62,4 +62,28 @@ 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 + if self =~ /\A((?:.+?#{sep}){#{words_count - 1}}.+?)#{sep}.*/m + $1 + (options[:omission] || '...') + else + dup + end + end end |