Forum: Ruby on Rails improving on: truncate(..) + rendered text ?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Ba3a00606eb530dcab2c4a6a59bf366d?d=identicon&s=25 Alain Ravet (Guest)
on 2007-03-29 09:23
(Received via mailing list)
Hello all,

In a summary page I need to show the 1st 100 chars of textilized
Problem: truncate(..) would often cut in the middle of html tags =>
random result.

My first idea was to "repair" the broken text with Hpricot (as I use
it elsewhere in the project), but it's not perfect:
would give

(I also use white_list to clean the <script>..)

I guess there are only 2 alternatives:
 - a smart html_truncate(..)
 - "unrender" the text (html => plain text)

Has anybody explored those directions?


Alain Ravet.
Ba3a00606eb530dcab2c4a6a59bf366d?d=identicon&s=25 Alain Ravet (Guest)
on 2007-03-29 17:46
(Received via mailing list)
Here is my 'improved' truncate that transforms html to text:

In sequence it :
  - sanitizes   (with white_list) and remove images
  - strips html tags => you're only left with plain text
  - truncates
  - simply_format => you get newlines and paragraphs back.


   WhiteListHelper.bad_tags   = %w(script img)
   def strip_and_truncate(text, length = 30, truncate_string = "...")
      if text.nil? then return end
      snip = truncate(strip_tags(white_list(text)), length,
This topic is locked and can not be replied to.