Tuesday, December 22, 2009

How to strip html tags, truncate and highlight texts in ruby on rails

Recently, I had the following requirements as I was working on CampZero.com - the going to be service marketplace of Bangladesh.
  1. Remove all html tags other than hyperlinks and new lines from a html fragment
  2. Truncate the text to show only first 200 characters of the text and append ellipsis (...) in case the text was truncated.
  3. Highlight an array of words in the text to show the search query worlds that matched
The first one, getting rid of all but hyperlinks and new lines was achieved by the following code:

<%= sanitize my_html_text, :tags => %w(br a) %>
Next, to truncate the text, I simply used the following:

<%= truncate my_sanitized_text, :length => 200 %>
Lastly, to highlight my search query words, I did the following

#in the controller
@query_words = params[:query] ? params[:query].split(/\W/) : ''
#in the view
In reality, I chained the above thee methods as shown below:
<%= highlight(truncate(sanitize(my_html_text, :tags => %w(br a)), :length => 200), @query_words) %>
These methods and their siblings are great as time savers. Rails makes the web development fun by including this as built in methods. For reference, you can check the link at SanitizeHelper and TextHelper
Happy railing!