NZisKool
NZisKool

Reputation: 239

truncate method truncating at random(?) length

I'm using truncate with a "read more" link in a Rails project. But very strangely, it's truncating the content at seemingly random places. Here's the code in my view:

<%= truncate(simple_format(article.content), length: 500, separator: ".", escape: false, omission: "... #{link_to("Read More", article}") %>

I measured the length where it's truncating and it's very random (like 278, 360, etc.). The split should happen at the end of a phrase (with separator: ".") and I'm checking if it could be related to that, but no. Even though there are other phrases within 500 chars, it splits way before.

Removing the omission argument actually solved it. I'm wondering why this happens.

Upvotes: 0

Views: 60

Answers (1)

NZisKool
NZisKool

Reputation: 239

The escaped HTML chars are actually counted in the length. This includes the link and title of your article.

By defaut in Rails, the link to your article will be something like /articles/1. But if you use a gem like friendly_id which creates slugged URLs such as /some-slugged-article-title, each article link will have a different length. This is what creates this variation in the truncating length.

In order to split around 500 characters of the visible text, you'll need to add the length of your article's title in the length argument. You can do so with this:

<%= truncate(simple_format(article.content), length: 500 + article.title.length, separator: ".", escape: false, omission: "... #{link_to("Read More", article)}") %>

Upvotes: 2

Related Questions