From ca72845c46f6e9d5166fe526b3335503be1f9d96 Mon Sep 17 00:00:00 2001 From: Steve St. Martin Date: Sat, 8 Aug 2009 20:40:28 -0400 Subject: [PATCH] backport truncate options[:seperator] --- actionpack/lib/action_view/helpers/text_helper.rb | 8 +++++++- actionpack/test/template/text_helper_test.rb | 3 +++ 2 files changed, 10 insertions(+), 1 deletions(-) diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index 8f1ddb9..173a33d 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -36,11 +36,16 @@ module ActionView # (defaults to 30). The last characters will be replaced with the :omission (defaults to "...") # for a total length not exceeding :length. # + # 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... # + # 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... # @@ -72,7 +77,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 diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index a370f14..85bd985 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -48,6 +48,9 @@ class TextHelperTest < ActionView::TestCase assert_equal "This is a string that wil[...]", truncate("This is a string that will go longer then the default truncate length of 30", :omission => "[...]") assert_equal "Hello W...", truncate("Hello World!", :length => 10) assert_equal "Hello[...]", truncate("Hello World!", :omission => "[...]", :length => 10) + assert_equal "Hello[...]", truncate("Hello Big World!", :omission => "[...]", :length => 13, :separator => ' ') + assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 14, :separator => ' ') + assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 15, :separator => ' ') end if RUBY_VERSION < '1.9.0' -- 1.6.4