public Method

TextHelper.truncate(text, length = 30, truncate_string = "...")

If text is longer than length, text will be truncated to the length of length (defaults to 30) and the last characters will be replaced with the truncate_string (defaults to "…").

Examples

truncate("Once upon a time in a world far far away", 14)
# => Once upon a...

truncate("Once upon a time in a world far far away")
# => Once upon a time in a world f...

truncate("And they found that many people were sleeping better.", 25, "(clipped)")
# => And they found that many (clipped)

truncate("And they found that many people were sleeping better.", 15, "... (continued)")
# => And they found... (continued)

Source Code

# File action_view/helpers/text_helper.rb, line 49
def truncate(text, length = 30, truncate_string = "...")
  if text
    l = length - truncate_string.chars.length
    chars = text.chars
    (chars.length > length ? chars[0...l] + truncate_string : text).to_s
  end
end
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.