aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/string/filters.rb
diff options
context:
space:
mode:
authorMatthew Draper <matthew@trebex.net>2014-07-17 04:31:18 +0930
committerMatthew Draper <matthew@trebex.net>2014-07-17 04:31:53 +0930
commit41679b2b31f88de2bf176197d883bc95dcb0a2f2 (patch)
tree551e871b3245b5af15f78d9bb43a4b6089a71d6d /activesupport/lib/active_support/core_ext/string/filters.rb
parentf636652dd52ed36f7438c0436679c987cdfefb82 (diff)
parenta9d3b77e494608cedcdad86d7e0c8a07694ffea5 (diff)
downloadrails-41679b2b31f88de2bf176197d883bc95dcb0a2f2.tar.gz
rails-41679b2b31f88de2bf176197d883bc95dcb0a2f2.tar.bz2
rails-41679b2b31f88de2bf176197d883bc95dcb0a2f2.zip
Merge pull request #16190 from oss92/word_truncation
Word truncation
Diffstat (limited to 'activesupport/lib/active_support/core_ext/string/filters.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/string/filters.rb24
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