In almost all the projects, client now wants feature to add,update content of website dynamically from admin panel. I mostly use CKEditor as rich text editor. Using CKEditor user can generate content with desired formatting.
This all formatting generate HTML content behind the scene. There are some case like listing articles or blogs, we need to show few lines of content and then by clicking on link show full content.
I use ActionView::Helpers::TextHelper#truncate method to show few content in listing.
There is case when you are truncating HTML content and some opened html tags are not closed because of truncation. There are couple of solution already available like
This plugin : https://github.com/hgmnz/truncate_html
I personally created simple helper method in application_helper.rb file and format the text.
As per my requirement I don’t need html content, I just want to truncate plain text. So I write following :
truncate(string.gsub(/(<[^>]+>)/, ''),length: length,omission: omission)
This function will remove tags from given string and truncate as per given parameters
Hope that helps!!