Careful when truncating strings

One of our Rails applications has to consume an RSS. Nothing fancy here, we simply wanted to extract some fields from each item and store them in the PostgreSQL DB (app was hosted on heroku).

Simply slicing the string seemed to work at first:

summary = entry.summary[0...255]

But soon we started obtaining PGError (incomplete multibyte character) when trying to persist our records in the DB. It seemed that the summary we were obtaining had a multibyte char in that position, and slicing the string seemed to slice the char itself.

Luckily, we were working on rails, and there is a helpful TextHelper truncate function to perform precisely the task we wanted.

include ActionView::Helpers::TextHelper
summary = truncate(entry.summary, :length => 255)

As a side note, trying to save the same sliced string in MySql, produced no errors whatsoever. Apparently, PostgreSQL is stricter than its counterpart.

Leave a Reply

Your email address will not be published. Required fields are marked *


five × = 40

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>