From a9d3b77e494608cedcdad86d7e0c8a07694ffea5 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 16 Jul 2014 19:48:07 +0200 Subject: Added truncate_words method to activesupport strings --- .../lib/active_support/core_ext/string/filters.rb | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'activesupport/lib/active_support/core_ext/string/filters.rb') 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 wordswords_count: + # + # 'Once upon a time in a world far far away'.truncate_words(4) + # # => "Once upon a time..." + # + # Pass a string or regexp :separator to specify a different separator of words: + # + # 'Once
upon
a
time
in
a
world'.truncate_words(5, separator: '
') + # # => "Once
upon
a
time
in..." + # + # The last characters will be replaced with the :omission 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 -- cgit v1.2.3