instance method
truncate
Ruby on Rails 2.3.18
Since v2.2.3Signature
truncate(text, *args)
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 “…”) for a total length not exceeding :length.
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", :length => 14)
# => Once upon a...
truncate("And they found that many people were sleeping better.", :length => 25, "(clipped)")
# => And they found t(clipped)
truncate("And they found that many people were sleeping better.", :omission => "... (continued)", :length => 25)
# => And they f... (continued)
You can still use truncate with the old API that accepts the length as its optional second and the ellipsis as its optional third parameter:
truncate("Once upon a time in a world far far away", 14) # => Once upon a... truncate("And they found that many people were sleeping better.", 25, "... (continued)") # => And they f... (continued)
Parameters
-
textreq -
argsrest
Source
# File actionpack/lib/action_view/helpers/text_helper.rb, line 61
def truncate(text, *args)
options = args.extract_options!
unless args.empty?
ActiveSupport::Deprecation.warn('truncate takes an option hash instead of separate ' +
'length and omission arguments', caller)
options[:length] = args[0] || 30
options[:omission] = args[1] || "..."
end
options.reverse_merge!(:length => 30, :omission => "...")
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
end
end
Defined in actionpack/lib/action_view/helpers/text_helper.rb line 61
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActionView::Helpers::TextHelper