Previewing a long Post or Article in Rails
I was tying to use truncate and htmlsafe to render the very first part of an article with a link to read more above the article and found that truncate and htmlsafe do not play well together. (That is a whole other story)
The articles that I wanted to preview had a title and then a body of text. I just wanted to render part of the body text.
Google search found this to use:
ruby
Nokogiri::HTML.parse(input_string).css('p').first.text
I just added on to that with:
ruby
Nokogiri::HTML.parse(input_string).css('p').first.text.html_safe.truncate(250)
This will parse the article to find the first "p" tag and get the text within that "p" tag. Then I call html_safe just in case there is HTML within the paragraph and finally I truncate the string to 250 characters.