Escaping HTML with Ruby on Rails

At work I had a small issue that just happened once and I couldn’t figure out why it didn’t work. The problem was a helper that truncated the text when it had more than 900 words in it and left JavaScript link that would show all the text. In this particular case something happened to the escaped text that the helper wouldn’t do its job. And as always I keep “magic” gems to a bare minimum in my projects.
After several tries and some researching, the following worked for me.

<div class='body-section__content' data-control='SHOW_MORE'>
  <% description = @place.description.try(:split, "\r\n").try(:join, '<br/>') || "" %>
  <%= description.try(:truncate, 900, separator: /\s/).try(:html_safe) %>
  <%= link_to 'See More', '#', class: 'js-show_more',
              data: { full_text: description.try(:html_safe) } if description.length > 900 %>
</div>

As I said this code would work fine most of the time but would suffer a lot with some characters. Line 3 can be replaced with this:

<%= raw description.truncate(900, omission: '') %>

I hope that this helps.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s