Skip to content
This repository
Browse code

Truncate helper accepts a :separator for a more legible result [#1807

…state:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information...
commit 5e190ef138a034bf86419ce4f4c343ae16bfc77b 1 parent 195fadb
Andy Stewart airblade authored lifo committed
7 actionpack/lib/action_view/helpers/text_helper.rb
@@ -34,12 +34,16 @@ def concat(string, unused_binding = nil)
34 34
35 35 # Truncates a given +text+ after a given <tt>:length</tt> if +text+ is longer than <tt>:length</tt>
36 36 # (defaults to 30). The last characters will be replaced with the <tt>:omission</tt> (defaults to "...").
  37 + # Pass a <tt>:separator</tt> to truncate +text+ at a natural break.
37 38 #
38 39 # ==== Examples
39 40 #
40 41 # truncate("Once upon a time in a world far far away")
41 42 # # => Once upon a time in a world f...
42 43 #
  44 + # truncate("Once upon a time in a world far far away", :separator => ' ')
  45 + # # => Once upon a time in a world...
  46 + #
43 47 # truncate("Once upon a time in a world far far away", :length => 14)
44 48 # # => Once upon a...
45 49 #
@@ -71,7 +75,8 @@ def truncate(text, *args)
71 75 if text
72 76 l = options[:length] - options[:omission].mb_chars.length
73 77 chars = text.mb_chars
74   - (chars.length > options[:length] ? chars[0...l] + options[:omission] : text).to_s
  78 + stop = options[:separator] ? (chars.rindex(options[:separator].mb_chars, l) || l) : l
  79 + (chars.length > options[:length] ? chars[0...stop] + options[:omission] : text).to_s
75 80 end
76 81 end
77 82
3  actionpack/test/template/text_helper_test.rb
@@ -49,6 +49,9 @@ def test_truncate_with_options_hash
49 49 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 => "[...]")
50 50 assert_equal "Hello W...", truncate("Hello World!", :length => 10)
51 51 assert_equal "Hello[...]", truncate("Hello World!", :omission => "[...]", :length => 10)
  52 + assert_equal "Hello[...]", truncate("Hello Big World!", :omission => "[...]", :length => 13, :separator => ' ')
  53 + assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 14, :separator => ' ')
  54 + assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 15, :separator => ' ')
52 55 end
53 56
54 57 if RUBY_VERSION < '1.9.0'

0 comments on commit 5e190ef

Please sign in to comment.
Something went wrong with that request. Please try again.