From 5e190ef138a034bf86419ce4f4c343ae16bfc77b Mon Sep 17 00:00:00 2001 From: Andy Stewart Date: Wed, 28 Jan 2009 16:45:28 +0000 Subject: Truncate helper accepts a :separator for a more legible result [#1807 state:resolved] Signed-off-by: Pratik Naik --- actionpack/lib/action_view/helpers/text_helper.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_view/helpers') diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index 8136a1cb13..ad0733a7e1 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -34,12 +34,16 @@ module ActionView # Truncates a given +text+ after a given :length if +text+ is longer than :length # (defaults to 30). The last characters will be replaced with the :omission (defaults to "..."). + # Pass a :separator to truncate +text+ at a natural break. # # ==== Examples # # truncate("Once upon a time in a world far far away") # # => Once upon a time in a world f... # + # truncate("Once upon a time in a world far far away", :separator => ' ') + # # => Once upon a time in a world... + # # truncate("Once upon a time in a world far far away", :length => 14) # # => Once upon a... # @@ -71,7 +75,8 @@ module ActionView if text l = options[:length] - options[:omission].mb_chars.length chars = text.mb_chars - (chars.length > options[:length] ? chars[0...l] + options[:omission] : text).to_s + stop = options[:separator] ? (chars.rindex(options[:separator].mb_chars, l) || l) : l + (chars.length > options[:length] ? chars[0...stop] + options[:omission] : text).to_s end end -- cgit v1.2.3