method

truncate

truncate(text, *args)
public

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)

1Note

Incompatible with Ruby 1.8.7

insane-dreamer ยท Mar 12, 20092 thanks

If using Rails < 2.2 with Ruby 1.8.7, calling truncate will result in the following error:

undefined method `length' for #<Enumerable::Enumerator:0xb74f952c>

The workaround (other than upgrading to Rails 2.2 or higher), is to overwrite the truncate method, by inserting the following at the end of environment.rb (or where it will be called on startup):

module ActionView
module Helpers
  module TextHelper
    def truncate(text, length = 30, truncate_string = "...")
      if text.nil? then return end
      l = length - truncate_string.chars.to_a.size
      (text.chars.to_a.size > length ? text.chars.to_a[0...l].join + truncate_string : text).to_s
    end
  end
end
end