Santiago Palladino

Santiago Palladino

Careful when truncating strings

2 min
Apr 20 2011
coding
2 min
Apr 20 2011

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.