mirror of
https://github.com/github/rails.git
synced 2026-04-26 03:00:59 -04:00
Truncate helper accepts a :separator for a more legible result [#1807 state:resolved]
Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
This commit is contained in:
committed by
Pratik Naik
parent
195fadbfd3
commit
5e190ef138
@@ -34,12 +34,16 @@ module ActionView
|
||||
|
||||
# Truncates a given +text+ after a given <tt>:length</tt> if +text+ is longer than <tt>:length</tt>
|
||||
# (defaults to 30). The last characters will be replaced with the <tt>:omission</tt> (defaults to "...").
|
||||
# Pass a <tt>:separator</tt> 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
|
||||
|
||||
|
||||
@@ -49,6 +49,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'
|
||||
|
||||
Reference in New Issue
Block a user