# Improving on: truncate(..) + rendered text?

**URL:** <https://www.ruby-forum.com/t/improving-on-truncate-rendered-text/90495>\
**Category:** Rails\
**Created:** [March 29, 2007, 9:23am UTC](https://www.ruby-forum.com/t/improving-on-truncate-rendered-text/90495 "2007-03-29T09:23:33Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![aravet](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/49beb7/32.png) [@aravet](https://www.ruby-forum.com/u/aravet)\
**Post date:** [March 29, 2007, 9:23am UTC](https://www.ruby-forum.com/t/improving-on-truncate-rendered-text/90495/1 "2007-03-29T09:23:33Z")

</div>

Hello all,

In a summary page I need to show the 1st 100 chars of textilized  
messages.  
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:

# abcd\</h would give

# abcd\</h

(I also use white\_list to clean the …)

I guess there are only 2 alternatives:

- a smart html\_truncate(…)  
or
- “unrender” the text (html =\> plain text)

Has anybody explored those directions?

TIA

Alain R…

---

<div class="post-metadata">

**Author:** ![aravet](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/49beb7/32.png) [@aravet](https://www.ruby-forum.com/u/aravet)\
**Post date:** [March 29, 2007, 5:46pm UTC](https://www.ruby-forum.com/t/improving-on-truncate-rendered-text/90495/2 "2007-03-29T17:46:26Z")

</div>

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.

code:

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,  
truncate\_string)  
simple\_format(snip)  
end
