Is there an HTML safe truncate method in Rails?

I have a string of HTML in Rails. I'd like to truncate the string after a certain number of characters not including the HTML markup. Also, if the split happens to fall in the middle of an opening and closing tag, I'd like to close the open tag/s. For example;

html = "123<a href='#'>456</a>7890"
truncate_markup(html, :length => 5) --> "123<a href='#'>45</a>"


There are two completely different solutions both with the same name: truncate_html

  1. : This is a gem and uses an html parser (nokogiri)
  2. : This is a file you put in your helpers directory. It uses regular expressions and has no dependencies.

the regular truncate function works fine, just pass :escape => false as an option to keep the HTML intact. eg:

truncate(@html_text, :length => 230, :omission => "" , :escape => false)

*Edit I didn't read the question very carefully (or at all TBH), so this answer does not solve this question... It IS the answer I happened to be looking for though, so hopefully it helps 1 or 2 people :)

Need Your Help

How Do I pass parameters with a render call?

ruby-on-rails parameters render

This is a simple question. If a form isn't filled out correctly, I call render 'new' in my create action so the person can fill out the form correctly. Unfortunately, this causes the loss of the

How do I install anacron?

linux virtual-machine crontab suse

I'm running on windows with a VM (SLES12). I wanted to automate a script and was using crontab at first, but it doesn't work when my system is off. So I looked into anacron, however I can't seem to...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.