method

truncate

rails latest stable - Class: ActionView::Helpers::TextHelper
truncate(text, options = {}, &block)
public

Truncates text if it is longer than a specified :length. If text is truncated, an omission marker will be appended to the result for a total length not exceeding :length.

You can also pass a block to render and append extra content after the omission marker when text is truncated. However, this content can cause the total length to exceed :length characters.

The result will be escaped unless escape: false is specified. In any case, the result will be marked HTML-safe. Care should be taken if text might contain HTML tags or entities, because truncation could produce invalid HTML, such as unbalanced or incomplete tags.

Options

:length

The maximum number of characters that should be returned, excluding any extra content from the block. Defaults to 30.

:omission

The string to append after truncating. Defaults to "...".

:separator

A string or regexp used to find a breaking point at which to truncate. By default, truncation can occur at any character in text.

:escape

Whether to escape the result. Defaults to true.

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: 17)
# => "Once upon a ti..."

truncate("Once upon a time in a world far far away", length: 17, separator: ' ')
# => "Once upon a..."

truncate("And they found that many people were sleeping better.", length: 25, omission: '... (continued)')
# => "And they f... (continued)"

truncate("<p>Once upon a time in a world far far away</p>")
# => "<p>Once upon a time in a wo..."

truncate("<p>Once upon a time in a world far far away</p>", escape: false)
# => "<p>Once upon a time in a wo..."

truncate("Once upon a time in a world far far away") { link_to "Continue", "#" }
# => "Once upon a time in a world...<a href=\"#\">Continue</a>"

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