12

I ran into a small problem today when I was trying to use sanitize and truncate in conjunction with one another to create an excerpt for my blog. Each of the methods worked by itself, but used together it would only truncate. I tried both of these syntaxes (the former being recommended in a blog post titled "Six Ruby on Rails Tips & Tricks"):

<%= truncate(sanitize(post.content), length: 580) %>
<%= sanitize(truncate(post.content, length: 580, separator: '<p>')) %>

And then I tried to put truncate in the controller, and sanitized that object in the view, but still no.

Finally I got it to work like this:

<%= sanitize(post.content.truncate(580, separator: '</p>')) %>

What I'd like to know is why didn't it work when I wrapped a method in another method? What's the difference with the last way I tried it?

TIA 'bondibox'

user2649201
  • 121
  • 4

4 Answers4

2

This worked for me:

<%=  sanitize(article.description[0..100]) %>
Ruben Portz
  • 174
  • 1
  • 10
0

Truncate and Sanitize are not included in controllers, they are part of ActionView::Helpers::TextHelper and ActionView::Helpers::SanitizeHelper respectively. These modules are not included per default in a controller, so you cannot use it in there.

However, both are included in the views (templates) and you can therefore use them in there. You can include the modules stated above in a controller class to use them there, but i would not recommend it.

The reason the second statement works is because Rails extends some base objects from Ruby, like String with several methods. so you actually call sanitize on a truncated version of a string truncated by a method of String.

The combination of both is a bit tricky. I cannot really tell you why the combination of the module version of sanitize and truncate does not work without a little more info. What exactly did you try to accomplish here (examples?)

Florian
  • 3,366
  • 1
  • 29
  • 35
0

An old question, but landed on it while struggling with this myself. The problem is that sanitize will not strip all HTML tags, but just a few that are defined by default, such as script. So you have to specifiy that no tags are allowed:

truncate sanitize(post.content, tags: [], attributes: []), length: 580

-2

Thanks Ruben,

<%=  sanitize(article.description[0..100]) %>

is working perfectly in Rails 6. Our experience is that all other combinations w/ truncate aren't working.

coopeu
  • 83
  • 5
  • Please post these kinds of answers as a comment under someone else's answer. That's also the best place to write a thank-you as long as it goes along with an upvote otherwise there's no benefit to the community in finding the best answers quickly. – Ruben Portz Sep 27 '21 at 20:17